java heap sort (big root heap)

The algorithm idea of ​​implementing heap sorting is to first create a heap, that is, compare the child nodes of each layer and their corresponding parent nodes from the leaf node, and replace the smaller parent node with the larger child node, level by level. By comparing and replacing, a large root heap is created, and a small root heap is vice versa. After creating the large root heap, we replace the root node of the entire tree with the last node, then remove the last node, create a new large root heap, and so on to complete the sorting. code show as below:

/**
* <p> HeapSort
* @param int[] arr
* @return int[]
* */
public int[] heapSort(int[] arr){

arr=creatHeap(arr,arr.length-1); //Initialize the big root heap
//Replace the big root to the corresponding last position each time, sort from back to
front for(int i=arr.length-1;i>0;i--){
int temp=arr[i];
arr [i]=arr[0];
arr[0]=temp;
creatHeap(arr,i-1);//Sort the rooted array into a large root heap again
}
return arr;
}

/**

		 * <p>Heap creation algorithm 
* @param int[] arr
* @return int[]
* */
public int[] creatHeap(int[] arr,int length){
System.out.println("Create a large root heap:" );
for(int i=length;i>0;i--){
int root=i;
int j=(root-1)/2;
/*Compare the leaf node with the root of the previous layer*/
while(root >0){
if(arr[root]>arr[j]){
int temp=arr[j];
arr[j]=arr[root];
arr[root]=temp;

}
/*Change position, compare above One layer and its parent node*/
root=j;
j=(root-1)/2;

}
}
for(int i=0;i<arr.length;i++){
System.out.print(" arr[" +i+"]="+arr[i]);
}
System.out.println("");
return arr;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325344317&siteId=291194637