一直不会堆排序,最近有一种冲动,将自己不会的东西好好整理一下,那就有了这篇堆排序的理解的梳理。
手推了一下堆排序的实现过程:

堆排序java具体实现代码如下:
public static void heapSort(int[] arrays, int rootLocation, int size){
int left = rootLocation*2+1;
int right = rootLocation*2+2;
int max=rootLocation;
if(left< size){
if(arrays[max] < arrays[left]){
max = left;
}
}
if(right < size){
if(arrays[max] < arrays[right]){
max = right;
}
}
if(max != rootLocation){
int temp = arrays[rootLocation];
arrays[rootLocation] = arrays[max];
arrays[max] = temp;
}
}
public static void maxHeapSortDeal(int[] arrays, int size){
for(int i=size-1;i>=0;i--){
heapSort(arrays,i,size);
}
int temp = arrays[0];
arrays[0] = arrays[size-1];
arrays[size-1] = temp;
}
public static void maxHeapSort(int[] arrays){
for(int i=0;i<arrays.length;i++){
maxHeapSortDeal(arrays, arrays.length-i);
}
}
public static void main(String[] args) throws Exception{
int[] arrays={4,5,2,1,3};
maxHeapSort(arrays);
for(int array:arrays){
System.out.println(array);
}
}
网友评论