您的位置:首页 > 其它

堆排序

2017-05-26 20:19 204 查看
堆排序是建立在完全二叉树的基础上的。首先理解什么是大顶堆(小顶堆类似),堆顶不小于下面的左子树和右子树。

同理,左子树和右子树同样符合上述要求。

堆排序分为以下步骤:

1、堆初始化,即建立大顶堆,从最后一个大于1个节点的子树开始进行调整,直至调整至整个堆的堆顶为止;

2、将堆顶元素与新重建堆的最后一个节点互换;

3、除新重建堆的最后一个节点外,对堆顶元素进行调整,重建大顶堆;

4、重复步骤2、3至最后一个节点止;

结过上述步骤,待排序数组即为有序数组,实例如下:

public class HeapSortMain {
public static void main(String[] args) {
int[] arr = {1,362,6,43,234,9,3,-45,2,5,1,9,2,6,7};
heapSort(arr);
System.out.println(Arrays.toString(arr));
}

//采用异或方式进行数据交换
static void change(int[] arr ,int index1,int index2){
arr[index1] ^= arr[index2];
arr[index2] ^= arr[index1];
arr[index1] ^= arr[index2];
}

//一次堆调整,即重建大顶堆
static void heapShift(int[] arr,int start,int end){
int right = (start+1)<<1;
int left = right-1;
int maxIndex = start;

if(left<=end && arr[maxIndex] < arr[left]) maxIndex= left;
if(right<=end && arr[maxIndex] < arr[right]) maxIndex= right;

if(maxIndex != start){
change(arr,maxIndex,start);
heapShift(arr,maxIndex,end);
}
}

//从最后一个大于1一个节点的子树的根开始,至整个树的根,建立完整的大顶堆
static void heapBuild(int[] arr){
int start = (arr.length-2)>>1;
int end = arr.length-1;
for(;start>=0;start--){
heapShift(arr,start,end);
}
}

//堆排序
static void heapSort(int[] arr){
heapBuild(arr);  //初始化建立大顶堆
for(int end=arr.length-1;end>0;end--){
change(arr,0,end);
heapShift(arr,0,end-1);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: