堆排序 java,
堆排序 java,
一个简单的堆排序
---源代码
public class heapify {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hellow");
int a[]={2,1,4,6,3,7,5};
heapSort(a,a.length);
int i;
for(i=0;i<a.length;i++){
System.out.print(a[i]+"");
}
}
//创建一个堆结点
public static void heapify(int a[],int i ,int size){
int left=i*2+1;
int right=i*2+2;
int largest=i;
if(left<size){
if(a[left]<a[i]) largest=left;
}
if(right<size){
if(a[right]<a[i]) largest=right;
}
if(largest!=i){
int temp=a[largest];
a[largest]=a[i];
a[i]=temp;
heapify(a,i,size);
}
}
//建立堆
public static void maxHeapify(int a[],int size){
int i;
for(i=size-1;i>=0;i--)
heapify(a ,i,size);
}
//堆排序
public static void heapSort(int a[],int size){
int i;
for(i=size-1;i>=0;i--)
{
maxHeapify(a,i+1);
int temp=a[i];
a[i]=a[0];
a[0]=temp;
}
}
}
相关文章
- 暂无相关文章
用户点评