堆排序
定义:是指利用堆这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的值总是小于(或者大于)它的父节点。
思想:
首先将待排序的数组构造成一个大根堆,此时,整个数组的最大值就是堆结构的顶端。然后将顶端的数与末尾的数交换,此时,末尾的数为最大值,剩余待排序数组个数为n-1。再将剩余的n-1个数再构造成大根堆,再将顶端数与n-1位置的数交换,如此反复执行,便能得到有序数组。
代码:
package xq0810;
public class HeapSort {
public static void heapsort(int []array) {
//将数组转化为堆结构,数组本来的初始化就是堆结构,不需要代码转化
//每一次都将堆排序的数组最大下标向前提一个
for(int end=array.length -1;end>0; end--) {
//将堆结构调整为大根堆
maxheap(array,end);
//将堆顶元素(此时堆顶元素是最大值,因为已经变成大根堆了)与最后一个叶子节点交换,完成排序
int temp=array[0];
array[0]=array[end];
array[end]=temp;
}
}
//end是大根堆元素的最大下标,就是最后一个叶子节点的元素下标
public static void maxheap(int [] array,int end) {
//找出最后一个父节点的下标 公式:(start+last)/2 然后向上取整在-1
int lastfather=(0 + end )%2 !=0 ? ( 0 + end )/2 :( 0 + end )/2 -1;
//从最后一个父节点开始向上一个父节点进行左右pk
for(int father=lastfather;father >= 0;father--) {
//定义父节点的左右下标
int left=2*father +1;
int right=2*father+2;
//如果右边比父节点大 则交换位置 。注意右边的需要判断是否超过数组元素的最大下标
if(right<= end && array[right]>array[father]) {
int temp=array[right];
array[right]=array[father];
array[father]=temp;
}
//如果左边比父节点大,则交换位置 最后变成大根堆
if(array[left]>array[father]) {
int temp=array[left];
array[left]=array[father];
array[father]=temp;
}
}
}
public static void main (String[] args) {
int []array = {1,2,5,6,8,9,7,10,55,66,44,99};
heapsort(array);
System.out.println("从小到大排序后的结果是:");
for(int i=0;i<array.length;i++)
System.out.print(array[i]+" ");
}
}
堆排序不是稳定的排序算法。