48.1 堆排序可能是排序算法中最难的,用到了二叉树。
48.2 建初始堆比较费劲。
48.3 调整堆的时间复杂度为O(log n),所以总体时间复杂度只有O(nlogn)。
48.4 空间复杂度只有O(1)。
代码:
/**
*******************
* Heap sort. Maybe the most difficult sorting algorithm.
*******************
*/
public void heapSort() {
DataNode tempNode;
//Step 1. Construct the initial heap.
for(int i = length / 2 -1;i>=0;i--) {
adjustHeap(i,length);
}//Of for i
System.out.println("The initial heap: " + this + "\r\n");
//Step 2. Swap and reconstruct.
for(int i = length - 1;i>0;i--) {
tempNode = data[0];
data[0] = data[i];
data[i] = tempNode;
adjustHeap(0,i);
System.out.println("Round " + (length - i) + ": " + this);
}//Of for i
}//Of heapSort
/**
*******************
* Adjust the heap.
*
* @param paraStart The start of the index.
* @param paraLength The length of the adjusted sequence.
*******************
*/
public void adjustHeap(int paraStart,int paraLength) {
DataNode tempNode = data[paraStart];
int tempParent = paraStart;
int tempKey = data[paraStart].key;
for(int tempChild = paraStart *2+1;tempChild<paraLength;tempChild = tempChild*2+1) {
//The right child is bigger.
if(tempChild + 1<paraLength) {
if(data[tempChild].key<data[tempChild+1].key) {
tempChild++;
}//Of if
}//Of if
System.out.println("The parent position is " + tempParent + " and the child is " + tempChild);
if(tempKey<data[tempChild].key) {
//The child is bigger.
data[tempParent] = data[tempChild];
System.out.println("Move " + data[tempChild].key + " to position " + tempParent);
tempParent = tempChild;
}else {
break;
}//Of if
}//Of for tempChild
data[tempParent] = tempNode;
System.out.println("Adjust " + paraStart + " to " + paraLength + ": " + this);
}//Of adjustHeap
/**
*******************
* Test the method.
*******************
*/
public static void heapSortTest() {
int[] tempUnsortedKeys = {5,3,6,10,7,1,9};
String[] tempContents = {"if","then","else","switch","case","for","while"};
DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);
System.out.println(tempDataArray);
tempDataArray.heapSort();
System.out.println("Result\r\n" + tempDataArray);
}//Of heapSortTest