[有错误]堆排序的实现 java
#include<iostream> using namespace std; //大根堆,从小到达排序 int a[101]; void swap(int &a,int &b) { a=a^b; b=a^b; a=a^b; } void adjust(int *a,int root,int len) { int max=root; int left=2*root; int right=2*root+1; if(left<=len&&a[max]<a[left]) { max=left; } if(right<=len&&a[max]<a[right]) { max=right; } if(max!=root) { swap(a[max],a[root]); adjust(a,max,len); } } void bulidHeap(int *a,int len) { for(int i=len/2;i>=1;i--) { adjust(a,i,len); } } void heapSort(int *a,int len) { if(len>1) { swap(a[1],a[len]); adjust(a,1,len-1);//调整为堆 heapSort(a,len-1); } } void output(int *a,int len) { for(int i=1;i<=len;i++) { cout<<a[i]<<" "; } cout<<endl; } int main() { while(!cin.eof()) { int len; cin>>len; for(int i=1;i<=len;i++) { cin>>a[i]; } bulidHeap(a,len); heapSort(a,len); output(a,len); } return 0; }
1 //一个大根堆的例子 2 //author:张小二 3 public class HeapSort { 4 public static void swap(int a[],int i,int j) 5 { 6 7 int temp=a[i]; 8 a[i]=a[j]; 9 a[j]=temp; 10 11 12 } 13 //最重要的自上而下调整的方法。,最多的代码在此处,建队和堆排序都是靠他。 14 public static void adjust(int a[],int i,int len)//调整以i为根 15 { 16 17 while(true) 18 { 19 int largest=i;//寻找 i,2i+1,2i+2中的最大值 20 int r=2*i; 21 int l=2*i+1; 22 if(r<len&&a[r]>a[largest]) largest=r; 23 if(l<len&&a[l]>a[largest]) largest=l; 24 if(largest==i) break; 25 26 swap(a,i,largest); 27 i=largest; 28 29 30 31 } 32 33 34 } 35 //建立堆,从最后一个非叶子开始 36 public static void bulid(int a[],int len) 37 { 38 display(a); 39 len=len-1; 40 for(int i=len/2;i>=0;i--) 41 { 42 adjust(a,i,len); 43 44 45 } 46 47 48 } 49 //堆排序 50 public static void heapSort(int a[]) 51 { 52 bulid(a,a.length); 53 54 55 int len=a.length-1; 56 while(len<1) 57 { 58 swap(a,0,len); 59 adjust(a,0,len); 60 len--; 61 62 63 } 64 //after 65 display(a); 66 } 67 68 public static void display(int a[]) 69 { 70 for(int i=0;i<a.length;i++) 71 { 72 System.out.print(a[i]+" "); 73 } 74 System.out.println(); 75 76 } 77 78 /** 79 * @param args 80 */ 81 public static void main(String[] args) { 82 // TODO Auto-generated method stub 83 int a[]={3,-3,5,6,-7,9,45}; 84 heapSort(a); 85 86 87 } 88 89 }