java代码
package cn.sunline.test;
/**
* @author huangzhongjie
*
*/
public class Heap {
public static void buildHeap(int[] arr) {
int iRoot = arr.length / 2 - 1;
for (; iRoot >= 0; iRoot--) {
moveElement(arr, iRoot, arr.length);
}
}
public static void moveElement(int[] arr, int iRoot, int iLength) {
int iLeft = iRoot * 2 + 1;
int iRight = iRoot * 2 + 2;
int iMaxInLeftRight = 0;
if (iLeft > iLength - 1) {
} else if (iLeft == iLength - 1) {
iMaxInLeftRight = iLeft;
if (arr[iLeft] > arr[iRoot]) {
swap(arr, iRoot, iMaxInLeftRight);
moveElement(arr, iMaxInLeftRight, iLength);
}
} else {
iMaxInLeftRight = arr[iLeft] > arr[iRight] ? iLeft : iRight;
if (arr[iMaxInLeftRight] > arr[iRoot]) {
swap(arr, iRoot, iMaxInLeftRight);
moveElement(arr, iMaxInLeftRight, iLength);
}
}
}
public static void swap(int[] arr, int i, int j) {
int iTemp;
iTemp = arr[i];
arr[i] = arr[j];
arr[j] = iTemp;
}
public static int[] sort(int[] arr) {
buildHeap(arr);
int[] arrResult = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
arrResult[i] = arr[0];
arr[0] = arr[arr.length - 1 - i];
moveElement(arr, 0, arr.length - 1 - i);
}
return arrResult;
}
public static void main(String[] args) {
int[] arr = { 12, 36, 24, 85, 47, 30, 53, 91 };
int[] arrResult = sort(arr);
for (int x : arrResult) {
System.out.print(x+ " ");
}
}
}