七大排序之:选择排序和堆排序

前面已经写了插入排序还有希尔排序。今天来描述一下选择排序还有堆排序。

三.选择排序

有两种方式,第一种是定义0下标为i,1下标为j;i不变j++,有比i小的就换到i的位置,直到走到最后面,找到第一个小的数字,之后i++,找到第二个第三个最小的数字。

第二种方法比第一种的好处在定义一个k,就不用一直换了,如果有小的就给k,之后换成i的位置。下面我来展示一下选择排序的代码:

    public static void selectSort(int[] array){
        for(int i=0;i<array.length-1;i++){
            for (int j = i+1; j < array.length; j++) {
                if(array[i]>array[j]){
                    swap(array,i,j);
                }
            }
        }
    }

 性能分析:

四.堆排序

基本原理也是选择排序,只是不在使用遍历的方式查找无序区间的最大的数,而是通过堆来选择无序区间的最大的数。

注意: 排升序要建大堆;排降序要建小堆。

 

 

    public static void heapSort(int[] array){
        //1.建堆 O(N)
        createHeap(array);
        int end=array.length-1;
        //2.交换然后调整 O(N*LOG N)
        while(end>0){
            swap(array,0,end);
            shiftDown(array,0,end);
            end--;
        }
    }

    public static void createHeap(int[] array){
        for (int parent = (array.length-1-1)/2; parent >=0 ; parent--) {
            shiftDown(array,parent,array.length);
        }
    }

    public static void shiftDown(int[] array,int parent,int len){
        int child=2*parent+1;//左孩子下标
        while(child<len){
            if(child+1<len&&array[child]<array[child+1]){
                child++;
            }
            if(array[child]>array[parent]){
                swap(array,child,parent);
                parent=child;
                child=2*parent+1;
            }else{
                break;
            }
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值