堆排序
1、堆排序
什么是堆?堆是一种完全二叉树,并且满足每个结点的值都不小于或者不大于其左右结点的值。再简单的说就是利用大顶推或者小顶堆进行排序。堆排序基本思路:将待排序的序列构造成一个大顶堆,这时整个序列最大值就是根节点,将根节点与堆得末尾结点进行交换后,剩下的结点重新构成一个大顶堆,此时,次大值就是根节点,重复进行上面步骤,就可以得到一个有序序列。
2、代码实现
public static void heapSort(){
int[] sort = { 68, 24, 91, 88, 6, 7, 5, 33, 10 };
int i;
for(i = sort.length/2-1; i >= 0; i--){
buildHeap(sort,i,sort.length); //调整为大顶堆
}
for (i = sort.length-1; i > 0; i--) {
swap(sort,0,i); //交换
buildHeap(sort,0,i); //重新构建大顶堆
}
for (int j = 0; j < sort.length; j++) {
System.out.println(sort[j]);
}
}
public static void buildHeap(int[] sort,int i,int n){
int temp ,child = 0;
for(temp = sort[i];(2*i+1) < n;i = child){
child = 2*i+1; //左孩子索引
if(child != n-1 && sort[child] < sort[child + 1])
child++;
if(temp < sort[child])
sort[i] = sort[child];
else
break;
}
sort[i] = temp;
}
public static void swap(int[] list,int i,int j){
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
开始,将他与其孩子结点进行比较和互换,构建堆得时间复杂度为 O(n) ,重建堆得时间复杂度为O(nlogn),所以平均时间
复杂度为O(nlogn)。堆排序性能远远高于简单排序、冒泡排序、直接插入排序时间复杂度的O(n²)。堆排序是一种不稳定
的排序。