堆排序(最大堆):
1、将数组作为一个未排序序列,给这个序列构建最大堆;
2、交换堆顶和未排序序列最后一个位置的元素值,最后一个位置的元素加入已排序序列;
3、由于交换导致未排序序列的最大堆受到影响,所以需要对未排序堆进行维护,让它维持最大堆,然后1,2操作循环直到未排序序列元素为0,既数组都排完序
代码如下:
package algorithm;
import java.util.Arrays;
public class HeapSort {
private static int num = 0;//循环次数
public static void sort(int[] forSort){
if(forSort == null || forSort.length < 0 ){
return ;
}
buildMaxHeap(forSort);
for(int i = forSort.length-1 ; i >= 1 ; i-- ){
swap(forSort, 0, i);
maxHeap(forSort, i, 0);
}
}
/**
* 建立初始最大堆顶
* @param forSort
*/
private static void buildMaxHeap(int[] forSort){
if(forSort == null || forSort.length < 0 ){
return ;
}
int half = (forSort.length/2-1);
for (int i = half; i >= 0; i--) {
maxHeap(forSort, forSort.length, i);
}
}
private static void maxHeap(int[] forSort,int heapSize ,int index){
num++;
int left = index * 2 + 1;
int right = index * 2 + 2;
int largest = index;
//一下两个if语句主要是为了从index 和 left 以及 right中取出最大的元素所在的索引
//如果index位置的元素比left元素小,则largest的值改为left
if(left < heapSize && forSort[index] < forSort[left]){
largest = left;
}
//如果largest位置的元素比right元素小,则largest的值改为right
if(right < heapSize && forSort[largest] < forSort[right]){
largest = right;
}
//如果最大元素的所以不是index则,需要将index和最大的元素进行交换,由于交换操作会导致已经处理好的符合最大堆定义的子树出现问题,所以需要从新更新受影响的树,是的整体依然符合最大堆
if(largest != index){
swap(forSort,index,largest);//交换位置
maxHeap(forSort,heapSize,largest);//维护最大堆
}
}
private static void swap(int[] forSort,int i, int j) {
int temp = forSort[i];
forSort[i] = forSort[j];
forSort[j] = temp;
}
public static void main(String[] args) {
// int[] array = {2,5,6,8,5,4,6,9,4,9};
int[] array = {2,5,6,8,5,4,6,9,4,9,-4,-6,45,54,67,0,8,4,-3,5,-23,-45,30};
long begintime = System.currentTimeMillis();
HeapSort.sort(array);
long endtime = System.currentTimeMillis();
System.out.println("最终结果:"+Arrays.toString(array)+",num="+num+",time="+(endtime-begintime));
}
}
执行结果如下:
最终结果:[-45, -23, -6, -4, -3, 0, 2, 4, 4, 4, 5, 5, 5, 6, 6, 8, 8, 9, 9, 30, 45, 54, 67],num=97,time=0