E 快速排序
:以下代码可以从数组a[]中找出第k小的元素。
它使用了类似快速排序中的分治算法,期望时间复杂度是O(N)的。
请仔细阅读分析源码,填写划线部分缺失的内容。
#include <stdio.h>
int quick_select(int a[], int l, int r, int k) {
int p = rand() % (r - l + 1) + l;
int x = a[p];
{int t = a[p]; a[p] = a[r]; a[r] = t;}
int i = l, j = r;
while(i < j) {
while(i < j && a[i] < x) i++;
if(i < j) {
a[j] = a[i];
j--;
}
while(i < j && a[j] > x) j--;
if(i < j) {
a[i] = a[j];
i++;
}
}
a[i] = x;
p = i;
if(i - l + 1 == k) return a[i];
if(i - l + 1 < k) return quick_select( _____________________________ ); //填空
else return quick_select(a, l, i - 1, k);
}
int main()
{
int a[] = {1, 4, 2, 8, 5, 7, 23, 58, 16, 27, 55, 13, 26, 24, 12};
printf("%d\n", quick_select(a, 0, 14, 5));
return 0;
}
1 #include <bits/stdc++.h> 2 using namespace std; 3 int quick_select(int a[], int l, int r, int k) 4 { 5 int p = rand() % (r - l + 1) + l; 6 int x = a[p]; 7 { 8 int t = a[p]; 9 a[p] = a[r]; 10 a[r] = t; 11 } 12 int i = l, j = r; 13 while(i < j) 14 { 15 while(i < j && a[i] < x) i++; 16 if(i < j) 17 { 18 a[j] = a[i]; 19 j--; 20 } 21 while(i < j && a[j] > x) j--; 22 if(i < j) 23 { 24 a[i] = a[j]; 25 i++; 26 } 27 } 28 a[i] = x; 29 p = i; 30 if(i - l + 1 == k) return a[i]; 31 if(i - l + 1 < k) return quick_select(a,i+1,r,k-(i-l+1)); 32 else return quick_select(a, l, i - 1, k); 33 } 34 int main() 35 { 36 int a[] = {1, 4, 2, 8, 5, 7, 23, 58, 16, 27, 55, 13, 26, 24, 12}; 37 printf("%d\n", quick_select(a, 0, 14, 5)); 38 return 0; 39 }