fork download
  1. #include <iostream>
  2. #include <time.h>
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <vector>
  6. #include <iostream>
  7. #include <algorithm>
  8. #include <assert.h>
  9.  
  10. using namespace std;
  11.  
  12.  
  13. int Pivot2(vector<int> &v, int pivot) {
  14.  
  15. vector<int> v_copy(v.size());
  16. //int pivot = v.size() / 2;
  17. //1. Sort the array about the mid term
  18. int count_less = 0;
  19. int j = 0;
  20. for (unsigned int i = 0; i <v.size() ; i++) {
  21.  
  22. if (v[i]< v[pivot]) {
  23. v_copy[j]=v[i];
  24. j++;
  25. count_less++;
  26. }
  27. }
  28.  
  29. v_copy[j]=v[pivot];
  30. j++;
  31.  
  32. for (unsigned int i = 0; i <v.size(); i++) {
  33.  
  34. if (v[i]> v[pivot]) {
  35. v_copy[j] = v[i];
  36. j++;
  37. }
  38. }
  39.  
  40. //2. if the number of less than than tmp_med increase the middle postion
  41. if ( count_less > v.size() / 2) {
  42. Pivot2(v_copy,count_less-1);
  43. }
  44. else if (count_less == v.size() / 2) {
  45. cout <<"inner " << v[pivot] <<endl ;
  46. return v[pivot]; //Why the recursion does not terminate with this return?
  47. }
  48. else {
  49. if ( count_less < v.size() / 2) {
  50. Pivot2(v_copy, count_less + 1 );
  51. }
  52. }
  53.  
  54.  
  55.  
  56. }
  57.  
  58.  
  59. int main() {
  60. // your code goes here
  61. int arr[] = { 8, 7, 3, 1, 9, 4, 6, 5, 2};
  62. int n = sizeof(arr) / sizeof(arr[0]);
  63. //randomize(arr, n);
  64. vector<int> v( begin(arr), end(arr) );
  65.  
  66. int med1 = Pivot2(v,v.size()/2);
  67. assert(5 == med1);
  68. cout << med1 <<endl ;
  69. return 0;
  70. }
Runtime error #stdin #stdout #stderr 0s 3468KB
stdin
Standard input is empty
stdout
inner 5
stderr
prog: prog.cpp:67: int main(): Assertion `5 == med1' failed.