伪最大堆排序HeapSort:
1、在这个排序中只想到把最大的值放到堆顶,没有注意到最大堆的定义:最大堆的任意子树中的根节点不小于该子树的子节点;
public class HeapSortCopy {
private static int num = 0;//循环次数
public int[] sort(int[] forSort,int lenght){
if (forSort == null || lenght <= 1) {
return forSort;
}
while(lenght>1){
for(int i=lenght/2-1;i>=0;i--){
num++;
int largest = i ;
if(2*i+1<=lenght-1 && forSort[i] < forSort[2*i+1]){
largest = 2*i + 1;
}
if(2*i+2<=lenght-1 && forSort[largest] < forSort[2*i+2]){
largest = 2*i+2;
}
//System.out.println("分次结果:"+Arrays.toString(forSort) +",i="+i);
if(largest != i) swap(forSort,i,largest);
}
swap(forSort,0,lenght-1);
lenght--;
// sort(forSort, lenght);
}
return forSort;
}
private void swap(int[] forSort,int i, int j) {
int temp = forSort[i];
forSort[i] = forSort[j];
forSort[j] = temp;
}
public static void main(String[] args) {
// int[] array = {2,5,6,8,5,4,6,9,4,9};
int[] array = {2,5,6,8,5,4,6,9,4,9,-4,-6,45,54,67,0,8,4,-3,5,-23,-45,30};
HeapSortCopy heapSort = new HeapSortCopy();
long begintime = System.currentTimeMillis();
heapSort.sort(array, array.length);
long endtime = System.currentTimeMillis();
System.out.println("最终结果:"+Arrays.toString(array)+",num="+num);
}
}
执行结果:
最终结果:[-45, -23, -6, -4, -3, 0, 2, 4, 4, 4, 5, 5, 5, 6, 6, 8, 8, 9, 9, 30, 45, 54, 67],num=132