1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| package com.zyg.sort;
public class HeapSortAlgorithm { public static void buildMinHeap(int a[], int len) { for (int i = len / 2; i >= 0; i--) adjustDown(a, i, len); } <!--more--> public static void adjustDown(int a[], int index, int len) { int temp = a[index]; for (int i = index * 2 + 1; i < len; i = i * 2 + 1) { if (i < len - 1 && a[i] > a[i + 1]) i++; if (temp < a[i]) break; a[index] = a[i]; index = i; } a[index] = temp; } public static void heapSort(int a[], int len) { buildMinHeap(a, len); System.out.println(a[0]); for (int i = len - 1; i > 0; i--) { swap(a, 0, i); adjustDown(a, 0, i); System.out.println(a[0]); } } public static void swap(int a[], int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } public static void main(String[] args) { int a[] = { 4, 3, 6, 7, 33, 15, 90, 65 }; heapSort(a, a.length); } }
|