package xxx;
public class HeapSort {
/**
* 在pos的子樹已經是大頂堆的前提下調整以pos爲根的二叉樹爲大頂堆
*/
public void adjustHeap(int[] array, int pos, int length) {
int childPos = 0;
// 持續沿子樹方向調整:較大元素上升,較小元素下沉
while ((childPos = 2 * pos + 1) < length) {
// 取兩棵子樹的樹根中較大元素交換
if (childPos + 1 < length) {
if (array[childPos] < array[childPos + 1])
childPos++;
}
// 需要交換:交換後繼續沿子樹方向調整
if (array[pos] < array[childPos]) {
int tmp = array[pos];
array[pos] = array[childPos];
array[childPos] = tmp;
pos = childPos;
}
// 不需交換:已經是大頂堆,停止沿子樹方向調整
else {
break;
}
}
}
/**
* 對array中的元素進行堆排序(遞增)
*/
public void heapSort(int[] array) {
// 建初始大頂堆
for (int i = array.length / 2 - 1; i >= 0; i--)
adjustHeap(array, i, array.length);
// N-1趟選擇-調整
for (int i = array.length - 1; i > 0; i--) {
int tmp = array[0];
array[0] = array[i];
array[i] = tmp;
adjustHeap(array, 0, i);
}
}
public static void main(String[] args) {
int[] array = new int[16];
java.util.Random random = new java.util.Random();
for (int i = 0; i < array.length; i++)
array[i] = random.nextInt(1000);
System.out.println("排序前:");
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
new HeapSort().heapSort(array);
System.out.println("排序後:");
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
}
}
堆排序程序
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.