zoukankan      html  css  js  c++  java
  • java实现选择排序

     1 public static void selectSort(int[] arr){
     2 
     3         //最开始除第一个元素外为未排序区间
     4         for (int i = 0; i < arr.length-1; i++) {
     5             int min = i;
     6             //遍历未排序区间,注意j的初始值,j比i大1
     7             for (int j = min + 1; j < arr.length; j++) {
     8                 //找出未排序区间的最小值的下标
     9                 if (arr[j] < arr[min]){
    10                     min = j;
    11                 }
    12             }
    13             //最小值下标不等于i,交换元素位置
    14             if (min != i){
    15                 int temp = arr[i];
    16                 arr[i] = arr[min];
    17                 arr[min] = temp;
    18             }
    19         }
    20     }
    21 
    22     public static void main(String[] args) {
    23         int[] arr = {5,3,2,6,1,4};
    24         SelectionSort.selectSort(arr);
    25         System.out.println(Arrays.toString(arr));
    26     }
    1.时间复杂度O(n^2)
    2.空间复杂度O(1),所以为原地排序算法
    3.不稳定 如[3,6,3,1,5],第一次3和1交换后,第一个3交换到了第二个3的后面
  • 相关阅读:
    shell_02
    shell_practise
    Shell_01
    PythonDay_03
    PythonDay_02
    PythonDay_01
    面试题32:从上到下打印二叉树
    面试题 31 : 栈的压入、弹出序列
    面试题20 : 表示数值的字符串
    面试题29:顺时针打印矩阵
  • 原文地址:https://www.cnblogs.com/fflower/p/12557087.html
Copyright © 2011-2022 走看看