您的位置:首页 > 编程语言

堆排序代码实现

2017-04-20 18:28 288 查看
public class Main {
public static void main(String[] args) {
int [] m = {1,4,5,6,3,9,2,11,22};
new Main().heapSort(m);
for(int i:m) System.out.println(i);
}
public void heapSort(int[] m){
for(int i=m.length-1;i>=0;i--){
HeapAdjust(m, i, m.length);
}
for(int i=m.length-1;i>0;i--){
int temp = m[i];
m[i] = m[0];
m[0] = temp;
HeapAdjust(m, 0, i);
}
}

/**
* 建立初始堆
* @param array
* @param parent 父节点
* @param length 长度
*/
public void HeapAdjust(int[] array, int parent, int length){
int temp = array[parent]; // temp保存当前父节点
int child = 2 * parent + 1; // 先获得左孩子
while (child < length) {
// 如果有右孩子结点,并且右孩子结点的值大于左孩子结点,则选取右孩子结点
if (child + 1 < length && array[child] < array[child + 1]) {
child++;
}
// 如果父结点的值已经大于孩子结点的值,则直接结束
if (temp >= array[child]) break;
// 把孩子结点的值赋给父结点
array[parent] = array[child];
// 选取孩子结点的左孩子结点,继续向下筛选
parent = child;
child = 2 * child + 1;
}
array[parent] = temp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: