《数据结构与算法分析——c语言描述》 第七章
算法真的很重要,选择问题是这本书一个循序渐进的例子。这次把复杂度强行降到O(N)。
#include<stdlib.h> #include<stdio.h> int RandInt(int i, int j) { int temp; temp = (int)(i + (1.0*rand() / RAND_MAX)*(j - i)); return temp; } void getRandomInt(int *A, int n) { for (int i = 0; i < n; i++) { A[i] = i + 1; } for (int i = 1; i < n; i++) { //std::swap(A[i], A[RandInt(0, i)]); int randAdrr = RandInt(0, i); int t = A[i]; A[i] = A[randAdrr]; A[randAdrr] = t; } } int a[99999999]; typedef int ElementType; void insertionSort(int *a, int n) { int j, p; int temp; for (p = 1; p < n; p++) { temp = a[p]; for (j = p; j > 0 && temp < a[j - 1]; j--) a[j] = a[j - 1]; a[j] = temp; } } void swap_my(ElementType *a, ElementType *b) { ElementType temp; temp = *a; *a = *b; *b = temp; } ElementType median3(ElementType a[], int left, int right) { int center = (left + right) / 2; if (a[left] > a[center]) swap_my(&a[left], &a[center]); if (a[left] > a[right]) swap_my(&a[left], &a[right]); if (a[center] > a[right]) swap_my(&a[center], &a[right]); swap_my(&a[center], &a[right - 1]); return a[right - 1]; } #define CUTOFF (3) void qSelect(ElementType a[], int k, int left, int right) { if (left + CUTOFF <= right) { int i, j; ElementType pivot; pivot = median3(a, left, right); i = left; j = right - 1; while (1) { while (a[++i] < pivot) {} while (a[--j] > pivot) {} if (i < j) swap_my(&a[i], &a[j]); else break; } swap_my(&a[i], &a[right - 1]);//把枢纽元换回来 if (k < i+1)//k从1开始,i从0开始,小于枢纽元 qSelect(a, k, left, i - 1); else if (k > i+1) qSelect(a, k, i + 1, right); } else { insertionSort(a + left, right - left + 1);//第k大的位于left和right之间,拍一下序 } } #define N 99999999 int main() { getRandomInt(a, N); int k; scanf("%d", &k); qSelect(a,k,0, N-1); printf("%d", a[k-1]); }