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,
  • 相关阅读:
    矩阵分析 p13~p20
    矩阵分析 p1~p13
    复变函数2
    口语80篇(1-2)
    复变函数1
    背单词方法
    writing practice
    将博客搬至CSDN
    windows内核编程 白话设备栈
    sfliter__except_handler4
  • 原文地址:https://www.cnblogs.com/lxyit/p/9404214.html
Copyright © 2011-2022 走看看