tag: 算法基本功 -> 排序 ->堆排序
堆排序原理:
所谓堆,是将以数组形式存储的数据结构逻辑上转换成完全二叉树,且对于非叶子节点满足如下定义:
arrs[i] >= arrs[2 * i + 1];
arrs[i] >= arrs[2 * i + 2];
需要调用[arrs.length / 2] 次可以判断是否为堆
建堆 -> 调整节点 -> 排序
package com.zhaochao.search;
/*1.build heap 2.adjust heap 3.heap sort minimum heap
*
* full binary tree
* */
public class HeapSort1 {
//build heap的过程就是从第n/2个数元素到0个元素adjust的过程
public void buildHeap(int[] heap,int size){
if(heap==null||heap.length==0){
return;
}
//int size = heap.length;
int index = size/2 - 1;
for(int i = index; i >= 0; i--){
headAdjust(heap,i,size);
}
return;
}
/* 1. 先把root root.left root.right 三者最小值得index求出来
* 2. 若 root不是最小值,则swap(root,minIndex,size),然后递归 headAdjust(heap,minIndex,size)
* */
public void headAdjust(int[] heap,int index,int size){
int left = index * 2 + 1;
int right = index * 2 + 1;
int minIndex = index;
if(left < size && heap[minIndex] > heap[left]){
minIndex = left;
}
if(right < size && heap[minIndex] > heap[right]){
minIndex = right;
}
if(minIndex != index){
swap(heap,index,minIndex);
headAdjust(heap,minIndex,size);
}
return;
}
/* build heap => 0与 index-i(i range:1,2,...,index-1) 逐步交换
* 1.把第0个元素与第n-1个元素swap,然后build第0到第n-2个元素
* */
public void heapSort(int[] heap){
int size = heap.length;
buildHeap(heap,size);
int index;
for(index = size - 1; index > 0; index--){
swap(heap,0,index);
headAdjust(heap,0,index - 1);
}
}
public void swap(int[] heap,int indexA,int indexB){
int tmp = heap[indexA];
heap[indexA] = heap[indexB];
heap[indexB] = tmp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] heap = {9,12,17,30,50,20,60,65,4,49};
HeapSort hs = new HeapSort();
hs.heapSort(heap, heap.length);
for(int i = 0; i < heap.length; i++){
System.out.print(heap[i]+" ");
}
}
}
原文:http://www.cnblogs.com/superzhaochao/p/6317192.html