您的位置:首页 > 职场人生

面试--算法排序(5)(堆排序)

2017-07-30 17:32 239 查看
堆排序也是选择排序的一种

堆的定义

如果有一个关键码K={k1,k2,k3…..}把他的所有元素按照完全二叉树的顺序存储方式放在一个一维数组中。并且满足

ki<=k2i且ki<=k2i+1//小根堆

ki>=k2i且Ki>=K2i+1//大根堆

小根堆效果图:



大根堆效果图



堆排序:

若在输出堆栈的最大值之后,使得剩余n-1个元素的序列又建成一个堆,则得到n个元素中的次大值,如此反复执行,便能得到一个有序序列,这个过程称为堆排序

*堆排序解决的两个问题:

①如何建堆

②输出堆顶元素之后,如何调整新堆*

代码展示:

import java.util.*;
public class HeapSort {
public int[] heapSort(int[] A, int n) {
int lastIndex = n - 1;
buildMaxHeap(A, lastIndex);//建立最大堆
while(lastIndex > 0){
swap(A, 0, lastIndex);
if(--lastIndex == 0)//只剩一个元素,就不用调整堆了,排序结束
break;
adjustHeap(A,0,lastIndex);
}
return A;
}
public void buildMaxHeap(int[] arr, int lastIndex) {
// 从最后一个元素的父节点开始进行调整,一直调整到根节点结束
int j = (lastIndex - 1) / 2;
while (j >= 0) {
int rootIndex = j;
adjustHeap(arr, rootIndex, lastIndex);
j--;
}

}
public void adjustHeap(int[] arr, int rootIndex, int lastIndex) {//从根节点开始往下调整
int biggerIndex = rootIndex;
int leftChildIndex = rootIndex * 2 + 1;
int rightChildIndex = rootIndex * 2 + 2;
if(rightChildIndex <= lastIndex){//如果右孩子存在,则左孩子一定存在
if(arr[rightChildIndex] > arr[rootIndex] || arr[leftChildIndex] > arr[rootIndex]){
//将子节点更大的元素下标赋值给biggerIndex
biggerIndex = arr[rightChildIndex] > arr[leftChildIndex]?rightChildIndex:leftChildIndex;
}
}
else if(leftChildIndex <= lastIndex){//保证左孩子存在,且不能越界
if(arr[leftChildIndex] > arr[rootIndex]){
biggerIndex = leftChildIndex;
}
}
if(biggerIndex != rootIndex){
swap(arr, biggerIndex, rootIndex);
adjustHeap(arr, biggerIndex, lastIndex);
}
}
public void swap(int[] arr, int biggerIndex, int rootIndex) {
int temp = arr[rootIndex];
arr[rootIndex] = arr[biggerIndex];
arr[biggerIndex] = temp;
}
}


算法分析:

平均时间复杂度:O(N*logN)

空间复杂度:O(1)

稳定性:不稳定
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  堆排序 算法
相关文章推荐