选择排序(不稳定)

选择排序 

方法一

思路图: 

代码: 

    //选择排序  时间复杂度O(n^2)  空间复杂度:O(n)   不稳定
    public static void selectSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int minIndex = i;
            for (int j = i+1; j < array.length; j++) {
                if (array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
            int temp = array[i];
            array[i] = array[minIndex];
            array[minIndex] = temp;
        }
    }

方法二

思路图:

代码:

    public static void selectSort2(int[] array) {
        int left = 0;
        int right = array.length-1;
        while (left < right) {
            int minIndex = left;
            int maxIndex = right;
            for (int i = left+1; i <= right; i++) {
                if (array[i] < array[minIndex]) {
                    minIndex = i;
                }
                if (array[i] > array[maxIndex]) {
                    maxIndex = i;
                }
            }
            swap(array,minIndex,left); //可能把最大值换到minIndex的位置  最大值正好在left

            if (maxIndex == left) {
                maxIndex = minIndex;
            }

            swap(array,maxIndex,right);
            left++;
            right--;
        }
    }
    private static void swap(int[] array,int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

堆排序

大根堆:每个节点的值都大于或者等于它左右孩子节点的值。

排序思想:

1、首先将待排序的数组构造成一个大根堆,此时,整个数组的最大值就是堆结构的顶端

2、将顶端的数与末尾的数交换,此时,末尾的数为最大值,剩余待排序数组个数为n-1

3、将剩余的n-1个数再构造成大根堆,再将顶端数与n-1位置交换,反复执行,便能得到有序数组

注意:升序用大根堆,降序用小根堆

 //堆排序
    public static void heapSort(int[] array) {
        createBigHeap(array);
        int end = array.length-1;
        while (end > 0) {
            swap(array,0,end);
            shiftDown(array,0,end);
            end--;
        }
    }
    private static void createBigHeap(int[] array) {
        for (int parent = (array.length-1-1)/2; parent >= 0; parent--) {
            shiftDown(array,parent,array.length);
        }
    }
    private static void shiftDown(int[] array,int parent,int len) {
        int child = 2*parent+1;
        while (child+1 < len ) {
            if (child+1 < len && array[child] < array[child+1]) {
                child++;
            }
            if (array[child] > array[parent]) {
                swap(array,child,parent);
                parent = child;
            }else {
                break;
            }
        }
    }
    private static void swap(int[] array,int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值