排序---选择排序,堆排序,冒泡排序

选择排序

基于打擂台的思想,每次从组中找到最小值,然后把最小值放到合适的位置
[0,bound)已排序区间
[bound,size)待排序区间
按照打擂台的方式,从待排序区间找一个最小值放到不bound位置上

public static void selectSort(int[] array){
    for (int bound = 0; bound < array.length; bound++) {
        //以bound位置作为擂主,循环从待排序区间中取出元素和bound位置元素比较
        //如果打擂成功就进行交换
        for (int cur = bound + 1; cur < array.length; cur++) {
            if(array[cur] < array[bound]){
                int tmp = array[cur];
                array[cur] = array[bound];
                array[bound] = array[cur];
            }
        }
    }
}

堆排序

把数建成一个大堆,把堆顶元素和最后一个元素进行交换,把最后一个元素删除,再从堆顶向下调整即可

public static void heapSort(int[] array){
    //先建立大堆
    createHeap(array);
    //循环地把堆顶元素交换到最后,并调整堆
    //循环次数length - 1,只剩最后一个元素有序
    for (int i = 0; i < array.length; i++) {
        //交换堆顶元素和最后一个元素
        //堆的元素array.length - 1
        swap(array,0,array.length - i -1);
        //最后一个元素的下标array.length - i - 1
        //[0,array.length - i -1)待排序区间
        //[array.length - i - 1,size)
        shiftDown(array,array.length - i - 1,0);
    }
}
private static void createHeap(int[] array) {
    for (int i = (array.length - 1 - 1) / 2; i >= 0 ; i--) {
        shiftDown(array,array.length,i);
    }
}
private static void shiftDown(int[] array, int size, int index) {
    int parent = index;
    int child = 2 * parent + 1;
    while(child < size){
        if(child + 1 < size && array[child + 1] > array[child]){
            child = child + 1;
        }
        if(array[parent] < array[child]){
            swap(array,parent,child);
        }else{
            break;
        }
        parent = child;
        child = 2 * parent + 1;
    }
}
private static void swap(int[] array, int i, int j) {
    int tmp = array[i];
    array[i] = array[j];
    array[j] = tmp;
}

冒泡排序

核心和堆排序很相似,每次找到最大或者最小值放在合适的位置
[0,bound) 待排序区间
[bound,size)已排序区间
从前往后遍历,找最大值
从后往前遍历,找最小值

public static void bubbleSort(int[] array){
    for(int bound = 0;bound < array.length;bound++){
        for(int cur = array.length - 1;cur > bound;cur--){
            if(array[cur - 1] > array[cur]){
                swap(array,cur - 1,cur);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值