1 void swap(int &i, int &j) 2 { 3 int temp = i; 4 i = j; 5 j = temp; 6 } 7 8 int partition(int a[], int p, int r) 9 { 10 int x = a[r]; 11 int i = p - 1; 12 for (int j = p; j < r; j++) { 13 if (a[j] <= x) { 14 i ++; 15 swap(a[i], a[j]); 16 } 17 } 18 i ++; 19 swap(a[i], a[r]); 20 return i; 21 } 22 23 int select(int a[], int p, int r, int i) { 24 int q = partition(a, p, r); 25 int k = q - p; 26 if (k == i) { 27 return a[q]; 28 } else if (k > i) { 29 return select(a, p, q - 1, i); 30 } else { 31 return select(a, q + 1, r, i - k - 1); 32 } 33 }
原文地址:https://www.cnblogs.com/ren-yu/p/11966306.html
时间: 2024-11-05 18:42:14