尋找數組中第k大的數


 在CODE上查看代碼片派生到我的代碼片
  1. #include <iostream>  
  2. #include <vector>  
  3. #include <algorithm>  
  4.   
  5. using namespace std;  
  6.   
  7. int partition(int arr[], int l, int r)  
  8. {  
  9.     int x = arr[r], i = l;  
  10.     for (int j = l; j <= r - 1; j++)  
  11.     {  
  12.         if (arr[j] <= x)  
  13.         {  
  14.             swap(arr[i], arr[j]);  
  15.             i++;  
  16.         }  
  17.     }  
  18.     swap(arr[i], arr[r]);  
  19.     return i;  
  20. }  
  21.   
  22. int GetKth(int* a, int low, int high,int k)  
  23. {  
  24.     int pivot;  
  25.     if (low < high)  
  26.     {  
  27.         pivot = partition(a,low,high);  
  28.         if ((pivot-low + 1) == k)  
  29.             return a[pivot];  
  30.         else if ((pivot-low + 1) > k)  
  31.             return  GetKth(a,low,pivot-1,k);  
  32.         else  
  33.             return GetKth(a, pivot+1,high, k);  
  34.     }  
  35. }  
  36. int main()  
  37. {  
  38.     int a[]={1,4,6,7,98,23,24,56};  
  39.     int n = 8, k = 3;  
  40.     cout << GetKth(a,0,7,3);  
  41.   
  42.   
  43. }  

原文:http://blog.csdn.net/u014682691/article/details/51029582


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章