美文网首页
堆排序(非递归版)

堆排序(非递归版)

作者: 林博伦 | 来源:发表于2019-12-08 13:22 被阅读0次

    时间复杂度是O(nlogN)

    • 但是不常用堆排序,因为堆排序不稳定
    堆排序.gif

    Java实现

        public static void heapSort(int[] arr) {
            if (arr==null || arr.length < 2) {
                return;
            }
            for(int i=0;i < arr.length;i++) {
                heapInsert(arr, i);
            }
            int heapSize = arr.length;
            swap(arr,0,--heapSize);
            while(heapSize>0) {
                heapify(arr, 0, heapSize);
                swap(arr,0,--heapSize);
            }
                
        }
        
        public static void heapInsert(int[] arr, int index) {
            while(arr[index] > arr[(index -1 )/2]) {
                swap(arr,index,(index - 1)/2);
                index = (index - 1)/2;
            }   
        }
        
        public static void heapify(int[] arr, int index, int heapSixe) {
            int left = index *2 + 1;
            while(left < heapSixe) {
                // largest 表示孩子中较大的坐标
                int largest = left + 1 < heapSixe && arr[left +1] > arr[left] ? left + 1 : left;
                largest = arr[largest] > arr[index] ? largest : index;
                if(largest == index) {
                    break;
                }
                // 当某个孩子比我大时执行,那个孩子的位置是largest      
                swap(arr, largest, index);
                index = largest;
                left = index *2 + 1;
                // 然后继续循环对此时的largest的孩子进行比较,直至到叶子
                // 即再次形成大根堆
            }
        }
        
        public static void swap(int[] arr,int i, int j)
        {
            int tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }
    

    相关文章

      网友评论

          本文标题:堆排序(非递归版)

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