代码:
1 #include<iostream> 2 #include<ctime> 3 4 using namespace std; 5 6 int size = 10; 7 8 void Swap(int &a, int &b) 9 { 10 int c = a; 11 a = b; 12 b = c; 13 } 14 15 void RandomizedSwap(int a[], int p, int r) 16 { 17 srand((int)time(0)); 18 int t = rand() % (r - p + 1)+p; 19 Swap(a[p], a[r]); 20 } 21 22 int RandomizedPartition(int a[], int p, int r) 23 { 24 RandomizedSwap(a, p, r); 25 int x = a[r]; 26 int i = p - 1; 27 for (int j = p; j < size - 1; j++) 28 { 29 if (a[j] < x) 30 { 31 i = i + 1; 32 Swap(a[j], a[i]); 33 } 34 } 35 Swap(a[i+1], a[r]); 36 return i + 1; 37 } 38 39 int RandomizedSelect(int a[], int p, int r, int i) 40 { 41 if (p == r) 42 return a[p]; 43 else 44 { 45 int q = RandomizedPartition(a, p, r); 46 if (q -p+1 == i) 47 return a[q]; 48 else 49 { 50 if (q -p +1 < i) 51 return RandomizedSelect(a, q + 1, r, i-q + p-1); 52 else 53 return RandomizedSelect(a, p, q - 1, i); 54 } 55 } 56 } 57 58 int main() 59 { 60 int a[] = { 16, 4, 10, 14, 7, 9, 3, 2, 8, 1 }; 61 cout << RandomizedSelect(a, 0, 9, 9) << endl; 62 }
时间: 2025-01-18 23:22:32