Heap Sort

作者: 綿綿_ | 来源:发表于2019-03-31 21:07 被阅读0次
public class HeapSort {
    static final int SIZE=15;
    static void heapSort(int a[],int n)
    {
        int i,j,h,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;
                }
            }
        }
        //print the heap
        System.out.print("the heap is below:");
        for(h=0;h<n;h++)
        {
            System.out.println(" "+a[h]);
        }
        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;
                }
            }
        }
    }
}

相关文章

网友评论

      本文标题:Heap Sort

      本文链接:https://www.haomeiwen.com/subject/wzaubqtx.html