/** ********************* * Selection sort. All data are valid. ********************* */ publicvoidselectionSort() { DataNode tempNode; int tempIndexForSmallest;
for (inti=0; i < length - 1; i++) { // Initialize. tempNode = data[i]; tempIndexForSmallest = i; for (intj= i + 1; j < length; j++) { if (data[j].key < tempNode.key) { tempNode = data[j]; tempIndexForSmallest = j; } // Of if } // Of for j
// Change the selected one with the current one. data[tempIndexForSmallest] = data[i]; data[i] = tempNode; } // Of for i }// Of selectionSort
/** ********************* * Heap sort. Maybe the most difficult sorting algorithm. ********************* */ publicvoidheapSort() { DataNode tempNode; // Step 1. Construct the initial heap. for (inti= 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 (inti= 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. ********************* */ publicvoidadjustHeap(int paraStart, int paraLength) { DataNodetempNode= data[paraStart]; inttempParent= paraStart; inttempKey= data[paraStart].key;
for (inttempChild= 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