八大排序算法之-堆排序 java代码

import java.util.Arrays;

/**
 * Created by Administrator on 2017/8/2.
 */
public class heapSort_select {
    public static void main(String args[]) {
        int[] arr = { 6, 9, 1, 3, 1, 2, 2, 5, 6, 1, 3, 5, 9, 7, 2, 5, 6, 1, 9 };
        //[1, 1, 1, 1, 2, 2, 2, 3, 3, 5, 5, 5, 6, 6, 6, 7, 9, 9, 9]
        heapSort(arr,0,arr.length-1);
        System.out.println(Arrays.toString(arr));
    }

    /*算法思想:
    * 大根堆:根部最大,可用于求最小k个数
    * 小根堆:根部最小,可用于求最大k个数
    *
    * 1.首先将序列构建成大根堆
    * 2.取出当前最大堆根节点,将其与序列末尾的元素进行交换;
    * (此时,序列末尾的值已经是最大值)
    * 3.对交换后的n-1个元素进行调整,使其满足大顶堆的性质
    * 4.重复2,3直到堆中只有一个元素为止*/

    /*时间复杂度:O(nlogn)
    * 空间复杂度:*/
    private static void heapSort(int[] arr, int start, int end) {
        /*if (arr==null || arr.length<=1) {

        }*/
        for (int i = 0; i<=end; i++) {
            heapInsert(arr,arr[i],i);
        }
        System.out.println(Arrays.toString(arr));

        for (int i = end - 1; i>=0; i--) {
            swap(arr,0,i+1);
            selfBalanceHeap(arr,0,i);
        }


    }

    private static void selfBalanceHeap(int[] heap, int index, int end) {
        int left = index * 2 + 1;
        int right = index * 2 + 2;
        int largest = index;
        while (left<=end) {
            if ( heap[left]>heap[index]) {
                largest = left;
            }
            if (right<=end && heap[right]>heap[largest]) {//此处应该和heap【largest】进行比较,即最大值,否则会出错
                largest = right;
            }
            if (index!=largest) {
                swap(heap,index,largest);
            }else {
                break;
            }
            index = largest;
            left = index*2 +1;
            right = index*2+2;
        }

    }

    private static void heapInsert(int[] heap, int value, int index) {
        heap[index] = value;
        while (index!=0) {
            int parent = (index - 1)/2;
            if (heap[parent] <heap[index]) {
                swap(heap,parent,index);
                index = parent;
            }else {
                break;
            }
        }
    }

    private static void swap(int[] heap, int parent, int index) {
        int tmp = heap[parent];
        heap[parent] = heap[index];
        heap[index] = tmp;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值