1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| int Partition(vector<int>& A , int start , int end){ int base = A[start]; int low = start; int high = end; while(low<high){ while(A[low]<=base){ low++; } while(A[high]>base){ high--; } if(low<high){ std::swap(A[low],A[high]) ; } } std::swap(A[high],A[start]); return high; } int main(){ int A[]={1,3,4,5,5,5,5,5,0}; vetcor<int> nums; nums.assign(A,A+sizeof(A)/sizeof(int)); int left = 0, right = nums.size()-1; int k = Partition(nums,left,right); int rankk=nums.size/2; while(k!=rankk){ if(k<rankk){ left = k; k = Partition(nums,left,right); }else if(k>rankk){ right = k; k = Partition(nums,left,right); } } cout<<"the result is " << nums[k]; }
|