《编程之美》——寻找最大的K个数(P139)
#define LeftChild(i) (2*(i)+1) static void swap(ElementType *lhs, ElementType *rhs) { ElementType tmp; tmp = *lhs; *lhs = *rhs; *rhs = tmp; } static void percdown(int *arr, int i, int n)//大根堆 { ElementType tmp; int child; for(tmp = arr[i]; LeftChild(i) < n; i = child) { child = LeftChild(i); if(child != n-1 && arr[child + 1] > arr[child]) child++; if(tmp < arr[child]) arr[i] = arr[child]; else break; } arr[i] = tmp; } void heap_sort(ElementType *arr, int n) { int i; for(i = n/2; i >= 0; i--) percdown(arr, i, n); for(i = n-1; i > 0; i--) { swap(arr, arr+i); percdown(arr, 0, i); } }快速排序
static void my_quick(ElementType *arr, int left, int right) { int i, j; ElementType pivot; if(left < right) { i = left; j = right+1; pivot = arr[left];//第一个元素作为枢纽元 while(1) { while(arr[++i] < pivot); while(arr[--j] > pivot); if(i < j) swap(arr+i, arr+j); else break; } swap(arr+j, arr + left); my_quick(arr, left, j-1); my_quick(arr, j+1, right); } } void quick_sort(ElementType *arr, int n) { my_quick(arr, 0, n-1); }解法二:修改快速排序算法用以解决选择问题,这种方法叫作快速选择(《数据结构与算法分析——C语言描述》P185),平均时间复杂度为O(NlogK)
static void my_qselect(ElementType *arr, int k, int left, int right) { int i, j, pivot; if(left < right) { i = left-1; j = right; pivot = arr[right];//最后一个元素做枢纽元,跟上面的快速排序相反。选择第一个作为枢纽元也可以 while(1) { while(arr[++i] > pivot); while(arr[--j] < pivot); if(i < j) swap(arr+i, arr+j); else break; } swap(arr+i, arr+right); if(k <= i) my_qselect(arr, k, left, i - 1); else if(k > i + 1) my_qselect(arr, k, i + 1, right); } } void quick_select(ElementType *arr,int k, int n)//快速选择 { my_qselect(arr, k, 0, n-1); }
static void shiftdown(ElementType *arr, int i, int n)//这里用的是小根堆 { int child; ElementType tmp; for(tmp = arr[i]; LeftChild(i) < n; i = child) { child = LeftChild(i); if(child != n-1 && arr[child+1] < arr[child]) child++; if(tmp > arr[child]) arr[i] = arr[child]; else break; } arr[i] = tmp; } void FindKth(ElementType *arr, ElementType *tmp, int k, int n)//最大的K个元素存放在tmp数组中 { int i; for(i = 0; i < k; i++) tmp[i] = arr[i]; for(i = k/2; i >= 0; i--) shiftdown(tmp, i, k); for(i = k; i < n; i++) { if(arr[i] > tmp[0]) { tmp[0] = arr[i]; shiftdown(tmp, 0, k); } } }