heapSort

来源:互联网 发布:批量修改后缀名软件 编辑:程序博客网 时间:2024/04/29 15:06
public class heapsort {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint[] a = {2,4,3,3,1,7,8,5};buildMaxHeap(a);for(int i : a)System.out.print(i + " ");System.out.println();buildMinHeap(a);for(int i : a)System.out.print(i + " ");System.out.println();for(int i : getKMin(a, 3))System.out.print(i + " ");System.out.println();for(int i : getKMax(a, 3)) System.out.print(i + " ");}//build the max heap//the whole time complexity: O(nlogn)public static void buildMaxHeap(int[] a){int n = a.length - 1;for(int i = n / 2; i >= 0; i--) {maxHeapity(a, i, n);}}// max heapitypublic static void maxHeapity(int[] a, int i, int n){while(i * 2 + 1 <= n) {int child = i * 2 + 1;if(child < n && a[child] < a[child + 1]) child++;if(a[i] < a[child]) {int tmp = a[i];a[i] = a[child];a[child] = tmp;i = child;}else return;}}//get the k min element from the input n elements//time complexity: O(nlogk)//space complexity: O(k)//it's better to get k elements from lots of elementspublic static int[] getKMin(int[] a, int k) {int[] heap = new int[k];for(int i = 0; i < k; i++) heap[i] = a[i];for(int i = (k - 1) / 2; i >= 0; i--) {maxHeapity(heap, i, k - 1);}for(int i = k; i < a.length; i++) {if(a[i] < heap[0]) {heap[0] = a[i];maxHeapity(heap, 0, k - 1);}}return heap;}//build the min heap//the whole time complexity: O(nlogn)public static void buildMinHeap(int[] a) {int n = a.length - 1;for(int i = n / 2; i >= 0; i--) {minHeapity(a, i, n);}}public static void minHeapity(int[] a, int i, int n) {while(2 * i + 1 <= n) {int child = 2 * i + 1;if(child < n && a[child] > a[child + 1]) child++;if(a[child] < a[i]) {int tmp = a[i];a[i] = a[child];a[child] = tmp;i = child;}else return;}}//get the k max element from the input n elements//time complexity: O(nlogk)//space complexity: O(k)//it's better to get k elements from lots of elementspublic static int[] getKMax(int[] a, int k) {int[] heap = new int[k];for(int i = 0; i < k; i++) heap[i] = a[i];for(int i = (k - 1) / 2; i >= 0; i--) {minHeapity(heap, i, k - 1);}for(int i = k; i < a.length; i++) {if(a[i] > heap[0]) {heap[0] = a[i];minHeapity(heap, 0, k - 1);}}return heap;}}

原创粉丝点击