Today sorted out the next heap sort, to an outsider's identity re-organized the heap sort (previously learned to forget) heap sorting based on the binary tree, review the binary tree, heap sorting is not difficult to write.
or the code.
Packagearithmetic;Importjava.util.Arrays; Public classHeapsort { Public Static voidMain (string[] args) {int[] arr = {9, 8, 7, 6, 5, 4, 3, 2, 1 }; Sort (arr); System.out.println (arrays.tostring (arr)); } Public Static voidSortint[] arr) { //1. Build a large top heap for(inti = ARR.LENGTH/2-1; I >= 0; i--) { //adjusts the structure from the first non-leaf node from bottom to top, right to left .adjustheap (arr, I, arr.length); } //2. Adjusting the heap structure + Exchange heap top element and end element for(intj = arr.length-1; J > 0; j--) {swap (arr,0, J);//swap the top element of the heap with the end elementAdjustheap (arr, 0, J);//to re-adjust the heap } } Public Static voidAdjustheap (int[] arr,intIintlength) { inttemp = Arr[i];//first remove the current element I for(intK = i * 2 + 1; K < length; K = k * 2 + 1) {//Starting at the left Dial hand node of the I node, which is 2i+1 . if(k + 1 < length && Arr[k] < Arr[k + 1]) {//If the left Dial hand node is small less right operand sub-node, K points to the right child node .k++; } if(Arr[k] > Temp) {//assigns the child node value to the parent node if the child node is larger than the parent node (no swapping)Arr[i] =Arr[k]; I= k;//nodes that hold larger values}Else { Break; }} Arr[i]= temp;//put the temp value in the final position } //Exchanging Data Public Static voidSwapintArr[],intAintb) {inttemp =Arr[a]; Arr[a]=Arr[b]; ARR[B]=temp; }}
Daily algorithm ———— heap sorting