#include <iostream> #include <ctime> using namespace std; int Partition(int A[],int low,int high) { int temp = A[low]; int i = low ,j = high; while (i < j) { while (i < j && A[j] >= temp) j--; while (i < j && A[i] <= temp) i++; swap(A[i],A[j]); } A[low] = A[i]; A[i] = temp; return i; } int RandomizedPartition(int A[],int low,int high) { int i = rand() % (high-low+1) + low; swap(A[i],A[low]); return Partition(A,low,high); } void QuickSort(int A[],int p,int r) { if (p < r) { int q = Partition(A,p,r); QuickSort(A,p,q-1); QuickSort(A,q+1,r); } } void RandomizedQuickSort(int A[],int p,int r) { if (p < r) { int q = RandomizedPartition(A,p,r); RandomizedQuickSort(A,p,q-1); RandomizedQuickSort(A,q+1,r); } } int RandomizedSelect(int A[],int low,int high,int k) { if (low == high) return A[low]; int i = RandomizedPartition(A,low,high); int j = i - low + 1; if (k <= j) return RandomizedSelect(A,low,i,k); else return RandomizedSelect(A,i+1,high,k-j); } int main(void) { int A[10]; int i; srand(time(NULL)); for (i = 0; i < 10;++i) { A[i] = rand() % 100; cout << A[i] << " "; } cout << endl; cout << RandomizedSelect(A,0,9,5) << endl; RandomizedQuickSort(A,0,9); for (i = 0; i < 10;++i) cout << A[i] << " "; cout << endl; return 0; }