package org.may.algorithm.heapsort;
/**
*
* @Description 堆排序,最坏时间复杂度O(n*logn) ,下标从1开始,非稳定排序
*
* @author H.John.May@gmail.com
*
* @CreateDate 2013/04/11
*
* 3
* / \
* 5 8
*
*/
public class HeapSort {
static void heapAdjust(int[] array,int len, int parent)
{
int lChild = parent * 2 ;
int rChild = parent * 2 + 1;
int max = parent;
while(lChild <= len)
{
if(array[lChild] > array[max]){
max = lChild;
}
if(rChild <= len && array[rChild] > array[max]){
max = rChild;
}
if(max != parent){
swap(array, parent, max);
parent = max;
lChild = parent * 2;
rChild = parent * 2 + 1;
}
else {
break;
}
}
}
static void swap(int[] array,int i,int j)
{
int t = array[i];
array[i] = array[j];
array[j] = t;
}
static void buildHeap(int[] array,int len)
{
for(int i = len/2 ; i >= 1; i--)
{
heapAdjust(array, len, i);
}
}
static void heapSort(int[] array)
{
int len = array.length - 1;
buildHeap(array, len);
while(len > 0)
{
swap(array, 1, len);
System.out.println(array[len]);
heapAdjust(array, --len, 1);
}
}
public static void main(String[] args)
{
int[] a = {0,5,7,4,8,23,56,79,13,17,31,140};
heapSort(a);
}
}
堆排序
最新推荐文章于 2023-09-21 13:21:58 发布