zoukankan      html  css  js  c++  java
  • java中的堆排序算法

    public static void heapsort(int[] a)
        {
            int len = a.length;
            //构建堆
            for(int i = len / 2 - 1;i >= 0 ;i-- )
            {
                heapadjust(a,i,len - 1);
            }
            for(int j=len -1;j>0;j--)
            {
                int temp = a[0];
                a[0] = a[j];
                a[j] = temp;
                heapadjust(a,0,j-1);
            }
        }
        
        public static void heapadjust(int[] a,int pos,int len)
        {
            int child = 2 * pos + 1;
            int tmp = a[pos];
            while(child <= len)
            {
                if(child <len && a[child] < a[child + 1])
                {
                    child ++;
                }
                if(a[child] >tmp)
                {
                    a[pos] = a[child];
                    pos = child;
                    child = 2*pos + 1;
                }
                else 
                {
                    break;
                }
            }
            a[pos] = tmp;
        }
        
        public static void main(String[] args) {
            int[] array = { 49, 38, 65, 97, 76, 13, 27, 50 };
            for(int i : array)
            {
                System.out.print(i + " ");
            }
            heapsort(array);
            System.out.println();
            for(int i = 0;i<array.length;i++)
            {
                System.out.print(array[i] + " " );
            }
        }
  • 相关阅读:
    CSS3--box-shadow
    C#快捷键
    c#基础3
    C#基础2
    C#基础
    javascript 字符串总结
    javasrcipt中的for in 循环
    javascript复习总结
    结构体数组排序
    ArrayList集合排序
  • 原文地址:https://www.cnblogs.com/suyun0702/p/12673457.html
Copyright © 2011-2022 走看看