最大堆的堆排序的Java实现
一.基本思想:
首先将所有元素(从未排过序的数组)插入堆中,然后从堆的根节点开始提取并且将最小的元素放到根节点然后堆化,直到完毕。
时间复杂度为O(nlogn).
二,排序代码如下:
//堆排序
int[] Heapsort(Heap h,int A[],int n)
{
int i,temp;
BuildHeap(h,A,n);
h.count=n;
for(i=n-1;i>=0;i--)
{
temp=h.array[0];
A[i]=temp;
h.array[0]=h.array[h.count-1];
h.count--;
h.PercolateDown(0);
}
return A;
}
完整代码如下:
Class Heap{
public int[] array;//存储元素的数组
public int count;//描述堆中存在元素的个数
public int capacity;//堆的大小
public int heap_type;//最大堆或最小堆
//创建堆构造方法
public Heap(int capacity,int heap_type)
{
this.capacity=capacity;
this.heap_type=heap_type;
this.count=0;
this.array=new int[capacity];
}