直接选择排序

一、排序过程

j从 i + 1 开始,mindIndex 记录值小于 i 下标所对应值的下标,初始值为i

因为 array[ j ] < array[ mindindex] 所以把 j 的值赋给mindindex,j++

后续重复这个过程

。。。

然后交换i 与 mindIndex 所对应的值

然后重复上述过程即可

二、代码实现

java 复制代码
    public static void selectSort(int[] arr) {
        for(int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for(int j = i + 1; j < arr.length; j++) {
                if(arr[j] < arr[minIndex]) {
                    mindIndex = j;
                }
            }
            if(minIndex != i) {
                int temp = arr[minIndex];
                arr[minIndex] = arr[i];
                arr[i] = temp;
            }
        }
    }

这个代码的时间复杂度是 O( N^ 2),效率很低

三、另一种写法

思路:定义left 位于最左端,right 位于最右端,一次循环,记录循环中的最大值和最小值,然后更新left 和 right ,再让 left++ ,right--,代码如下:

java 复制代码
    public static void selectSort(int[] arr) {
        int left = 0;
        int right = arr.length - 1;
        while(left < right) {
            int minIndex = left;
            int maxIndex = left;
            for(int i = left + 1; i <= right; i++) {
                if(arr[i] < arr[minIndex]) {
                    minIndex = i;
                }
                if(arr[i] > arr[maxIndex]) {
                    maxIndex = i;
                }
            }
            swap(arr,left,minIndex);
            if(maxIndex == left) {
                maxIndex = minIndex;
            }
            swap(arr,maxIndex,right);
            left++;
            right--;
        }
    }
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

为什么要加入maxIndex == left?

有一种情况是left 本身已经指向最大的元素了,然后minIndex 依旧与它交换,然而最大值maxIndex已经确定完毕,right已经修改了,加入这行代码可以解决

当然,时间复杂度仍然是 O( N^ 2)

相关推荐
OOJO3 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
田梓燊5 小时前
code 560
数据结构·算法·哈希算法
会编程的土豆5 小时前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
迈巴赫车主7 小时前
蓝桥杯19724食堂
java·数据结构·算法·职场和发展·蓝桥杯
Kethy__7 小时前
计算机中级-数据库系统工程师-数据结构-查找算法
数据结构·算法·软考·查找算法·计算机中级
所以遗憾是什么呢?7 小时前
【题解】Codeforces Round 1081 (Div. 2)
数据结构·c++·算法·acm·icpc·ccpc·xcpc
OOJO8 小时前
c++---vector介绍
c语言·开发语言·数据结构·c++·算法·vim·visual studio
茉莉玫瑰花茶8 小时前
数据结构 - 并查集
数据结构
汀、人工智能8 小时前
05 - 函数基础
数据结构·算法·数据库架构·05 - 函数基础
计算机安禾10 小时前
【数据结构与算法】第28篇:平衡二叉树(AVL树)
开发语言·数据结构·数据库·线性代数·算法·矩阵·visual studio