堆排序

来源:互联网 发布:linux 新建用户组 编辑:程序博客网 时间:2024/06/08 06:10
package coding;public class cha04_heapSort {    static final int SIZE=10;    static void heapSort(int []a,int n){        int i,j, k;        int t;        for(i=n/2-1;i>=0;i--){            while(2*i+1<n){                                             j=2*i+1;                if((j+1)<n){                    if(a[j]<a[j+1]){                     j++;                       }                }                    if(a[i]<a[j]){                        t=a[i];                        a[i]=a[j];                        a[j]=t;                        i=j;                    }                    else{                        break;                    }                }            }            System.out.print("原始数据构成的堆:");            for(int h=0;h<n;h++){                System.out.print(" "+a[h]);            }            System.out.println();            for(i=n-1;i>0;i--){                t=a[0];                a[0]=a[i];                a[i]=t;                k=0;                while(2*k+1<i){                    j=2*k+1;                    if((j+1)<i){                        if(a[j]<a[j+1]){                            j++;                        }                    }                        if(a[k]<a[j]){                            t=a[k];                            a[k]=a[j];                            a[j]=t;                            k=j;                        }                        else{                            break;                        }                    }                    System.out.print("第"+(n-i)+"步排序的结果:");                    for(int h=0;h<n;h++){                        System.out.print(" "+a[h]);                    }                    System.out.println();            }                   }    public static void main(String[] args) {        // TODO Auto-generated method stub        int [] shuzu=new int[SIZE];           int i;           for(i=0;i<SIZE;i++){               shuzu[i]=(int)(100+Math.random()*(100+1));           }           System.out.print("排序前的数组:");           for(i=0;i<SIZE;i++){               System.out.print(shuzu[i]+" ");           }           System.out.println();           heapSort(shuzu,SIZE);           System.out.print("排序后的数组为:");           for(i=0;i<SIZE;i++){                       System.out.print(shuzu[i]+" ");           }           System.out.println();        }    }
0 0
原创粉丝点击