选择排序

2022/6/14 23:23:31

本文主要是介绍选择排序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

选择排序

  • 原理

    • 第一次从数据中选出最小的元素,放置序列的起始位置 \([0,n-1]\)
    • 第二次从数据中选出最小的元素,放置序列第二个位置 \([0,n-2]\)
    • ...
  • 排序过程

    • 原始序列:{7, 1, 3, 2, 5, 8}
      第一次:{1,7,3,2,5,8}
      第二次:{1,2,3,7,5,8}
      第三次:{1,2,3,7,5,8}
      第四次:{1,2,3,5,7,8}
      

代码实现

public class Solution {
    
    public void selectSort(int[] arr) {
        int len = arr.length;
        for (int i = 0; i < len; i++) {
            int minIndex = i;
            for (int j = i + 1; j < len; j++) {
                minIndex = arr[minIndex] > arr[j] ? j : minIndex;
            }
//            交换两个元素
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
            
        }
        
    }
}


这篇关于选择排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程