输入n个整数,输出其中最小的k个。
例如输入1,2,3,4,5,6,7和8这8个数字,
则最小的4个数字为1,2,3和4。
构建一个K个元素的堆,最终的算法复杂度为K*log(n)
#include "stdafx.h" #include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /** * @brief max_heapify, filter up a heap * * @param heap[] * @param s start index * @param e end index * * @return 0 */ int max_heapify(int heap[], int s, int e) { int rc; int i; rc = heap[s]; for (i = 2*s + 1; i <= e; i = 2*i + 1) { if ((i + 1) <= e && heap[i] <= heap[i+1]){ i++; } if (heap[i] < rc){ break; } heap[s] = heap[i]; s = i; } heap[s] = rc; return 0; } /* * Build a max heap */ int build_max_heap(int heap[], int heap_size) { int i; for (i = heap_size/2-1; i >= 0; i--) { max_heapify(heap, i, heap_size-1); } return 0; } /* * Add one value to heap and adjust it */ int add_one_vaule(int heap[], int heap_size, int val) { /* We need k-min values */ if (val < heap[0]){ heap[0] = val; max_heapify(heap, 0, heap_size-1); } return 0; } /* * Find K min values */ int find_k_min(int data[], int len, int k) { int *heap; int i; heap = (int *)malloc(k * sizeof(int)); if (heap == NULL){ printf("Malloc error!\n"); return -1; } for (i = 0; i < k; i++) { heap[i] = data[i]; } build_max_heap(heap, k); for (; i < len; i++) { add_one_vaule(heap, k, data[i]); } for (i = 0; i < k; i++) { printf("%d,", heap[i]); } printf("\n"); free(heap); return 0; } int main() { int data[] = {8, 3, 2, 10, 5, 7, 9, 1, 4, 0, 7}; int len = sizeof(data) / sizeof(data[0]); find_k_min(data, len, 4); return 0; }