堆排序 java实现

来源:互联网 发布:10年nba总决赛数据 编辑:程序博客网 时间:2024/04/28 16:18
package sort;
/*堆排序  
 * 构建堆的时间复杂度为哦O(n)
 * 第i次取堆顶记录重建需要用O(log i)的时间,需要n-1次堆顶记录,因此时间复杂度为O(nlog n)
 * 适合待排序序列元素较多的情况
 */
public class HeapSort {


public static void main(String[] args) {
// TODO 自动生成的方法存根
int a[]={0,2,6,9,8,7,5,3,4,1};
int b[]=heapsort(a);
printsort(b);


}
//数组打印函数
public static void printsort(int a[])
{
for(int k=0;k<a.length;k++)
System.out.println(a[k]);
}
//元素交换
public static void swap(int []c, int a,int b)
{
int temp=c[a];
c[a]=c[b];
c[b]=temp;
}
public static int[] heapsort(int a[])
{
int i;

//构建大顶堆,只需要(a.length-1)/2个父节点就可以构造
for(i=(a.length-1)/2;i>0;i--)
heapAdjust(a,i,a.length-1);

for(i=a.length-1;i>1;i--)
{
swap( a, 1, i);//将堆顶值与最后一个叶子结点交换
heapAdjust(a,1,i-1); //将剩余元素调整成大顶堆
}

return a;
}
//调整大顶堆函数
public static void heapAdjust(int []a,int s,int m)
{
int temp,j;
temp=a[s];
for(j=2*s;j<=m;j*=2)
{
if(j<m&&a[j]<a[j+1])
++j;
if(temp>=a[j])
break;
a[s]=a[j];
s=j;
}
a[s]=temp;
}


}
1 0
原创粉丝点击