排序-堆排序

// heapSort 是跟着视频学习写的
// headSort2 是我自己想的,感觉这么写可以。。。验证是ok的。 
// 区别等我问问。。。


import com.alibaba.fastjson.JSON;

/**
 * @author : wangtb
 * @date : 2019-09-29 23:02
 */
public class HeapSort {


    public static void main(String[] args) {
        int arr[] = {6, 2, 0, 1, 8, 20,10,100,-1};
        heapSort(arr);


        //System.out.println(JSON.toJSONString(arr));
        heapSort2(arr);

    }

    /**
     * 貌似也行啊 是因为时间复杂度不好吗?
     * @param arr
     */
    private static void heapSort2(int[] arr) {
        //先转成一个大根堆
        int size = arr.length - 1;
        while (size > 0) {
            for (int i = 0; i <= size; i++) {
                headInsert(arr, i);
            }
            //System.out.println(JSON.toJSONString(arr));
            swap(arr, 0, size);
            size--;
        }
        //System.out.println(JSON.toJSONString(arr));
    }


    public static void heapSort(int arr[]) {
        if (arr == null || arr.length < 2) {
            return;
        }
        //先转成一个大根堆
        for (int i = 0; i < arr.length; i++) {
            headInsert(arr, i);
        }
        System.out.println(JSON.toJSONString(arr));
        //
        int heapSize = arr.length;
        swap(arr, 0, --heapSize);
        System.out.println(JSON.toJSONString(arr));
        while (heapSize > 0) {
            heapify(arr, 0, heapSize);
            //headInsert(arr,heapSize);
            swap(arr, 0, --heapSize);
        }
    }

    //初次形成大根堆
    public static void headInsert(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 heapSize) {
        int left = index * 2 + 1;
        while (left < heapSize) {
            //比左右哪2个大
            int largest = left + 1 < heapSize && arr[left + 1] > arr[left] ? left + 1 : left;
            largest = arr[largest] > arr[index] ? largest : index;
            if (largest == index) {
                break;
            }
            swap(arr, largest, index);
//            System.out.println("heapify start, heapsize = " + heapSize);
//            System.out.println(JSON.toJSONString(arr));
//            System.out.println("heapify end");
            index = largest;
            left = index * 2 + 1;
        }
    }


    public static void swap(int arr[], int a, int b) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值