zoukankan      html  css  js  c++  java
  • 排序算法 — 选择排序

    /**
     * 选择排序
     *
     * <p>算法思路:
     *
     * <p>1.遍历数列,找到最小(或最小)元素,然后将其放到数列首位,作为已排序部分
     *
     * <p>2.对剩下待排序数列,重复以上第一步,找到最小(或最小)元素放到已排序的部分后面,直到无待排序部分
     *
     * 算法复杂度:O(n²)
     * 稳定性:不稳定
     * @author lxy
     */
    public class SelectionSort {
    
      /**
       * 交换
       */
      private static void swap(int[] array, int m, int n) {
        int tmp = array[m];
        array[m] = array[n];
        array[n] = tmp;
      }
    
      public static int[] selectSort(int[] array) {
        // 边界情况处理
        if (array == null || array.length == 0) {
          throw new IllegalArgumentException("array must be not empty!");
        }
        if (array.length == 1) {
          return array;
        }
    
        // 两步for,第一个for是遍历一次,第二个for循环遍历
        for (int i = 0; i < array.length; i++) {
          // 记录最小数槽位
          int index4Smallest = i;
          for (int j = i + 1; j < array.length; j++) {
            if (array[j] < array[index4Smallest]) {
              index4Smallest = j;
            }
          }
          // 交换
          swap(array, i, index4Smallest);
        }
        return array;
      }
    
    
      /**
       * 测试
       */
      public static void main(String[] args) {
        int[] array = {9, 8, 11, 17, 12, 2, 4, 5, 20, 3, 1};
        System.out.println("选择排序前:");
        for (int i = 0; i < array.length; i++) {
          System.out.print(array[i]);
          System.out.print(",");
        }
        array = SelectionSort.selectSort(array);
        System.out.println("
    选择排序后:");
        for (int i = 0; i < array.length; i++) {
          System.out.print(array[i]);
          System.out.print(",");
        }
      }
    }
    
    

    执行结果:

    选择排序前:
    9,8,11,17,12,2,4,5,20,3,1,
    选择排序后:
    1,2,3,4,5,8,9,11,12,17,20,
  • 相关阅读:
    基于日志实现ssh服务防护脚本
    给多主机传输文件脚本
    Python map() 函数
    常用希腊字母读法
    Python中Numpy.nonzero()函数
    numpy.eye() 生成对角矩阵
    (sklearn)岭回归 sklearn.linear_model.Ridge用法
    pip配置永久国内源
    python numpy的var std cov研究
    numpy中的mean()函数
  • 原文地址:https://www.cnblogs.com/lxyit/p/9404214.html
Copyright © 2011-2022 走看看