zoukankan      html  css  js  c++  java
  • 排序算法练习之选择排序

    练习练习练习!!!

    import java.util.Arrays;
    
    /**
     * @Date: 2019-11-24 09:20
     * @King: No blood!No bone!No ash!!!
     */
    public class TestSelectionSort {
      public static void main(String[] args) {
        /**
         * 定义数组
         */
        int [] arr = new int[7];
        arr[0] = 31;
        arr[1] = 13;
        arr[2] = 21;
        arr[3] = 33;
        arr[4] = 10;
        arr[5] = 25;
        arr[6] = 11;
        /**
         * 输出排序前
         */
        System.out.println("排序前:"+ Arrays.toString(arr));
        /**
         * 调用两种选择排序方法,并输出结果
         */
        selectionSortI(arr);
        System.out.println("无返回值类型排序后:"+Arrays.toString(arr));
        selectionSortII(arr);
        System.out.println("有返回值类型排序后:"+Arrays.toString(arr));
      }
    
      /**
       * 无返回值类型的选择查找
       */
      public static void selectionSortI (int [] array) {
        /**
         * 外层循环控制排序趟数
         */
        for (int i = 0;i < array.length - 1;i++) {
          for (int j = i;j < array.length - 1;j++) {
            /**
             * 假设每趟循环开始位置的元素最小,下标为minIndex = i
             */
            int minIndex = i;
            /**
             * 一趟循环结束发现比array[minIndex]小的元素,将其下标赋给minIndex
             * 一趟循环结束后将最小元素与开始元素交换位置
             */
            if (array[minIndex] > array[j + 1]) {
              minIndex = j + 1;
            }
            int temp = array[minIndex];
            array[minIndex] = array[i];
            array[i] = temp;
          }
        }
      }
      /**
       * 有返回值类型的选择查找
       */
      public static int [] selectionSortII (int [] array) {
        if (array.length == 0) {
          return array;
        }
        for (int i = 0;i < array.length - 1;i++) {
          int minIndex = i;
          for (int j = i;j < array.length - 1;j++) {
            if (array[minIndex] > array[j+1]) {
              minIndex = j + 1;
            }
            int temp = array[minIndex];
            array[minIndex] = array[i];
            array[i] = temp;
          }
        }
        return array;
      }
    }

    运行结果:

    排序前:[31, 13, 21, 33, 10, 25, 11]
    无返回值类型排序后:[10, 11, 13, 21, 25, 31, 33]
    有返回值类型排序后:[10, 11, 13, 21, 25, 31, 33]

    尽量让自己养成编程保证程序健壮性的习惯!

  • 相关阅读:
    浏览器原理
    jQ插件编写
    [转]清理浮动的全家
    百度面试~~
    LeetCode-222. Count Complete Tree Nodes
    LeetCode-236. Lowest Common Ancestor of a Binary Tree
    LeetCode-235. Lowest Common Ancestor of a Binary Search Tree
    LeetCode-102. Binary Tree Level Order Traversal
    LeetCode-404. Sum of Left Leaves
    LeetCode-257. Binary Tree Paths
  • 原文地址:https://www.cnblogs.com/sinoaccer/p/11921539.html
Copyright © 2011-2022 走看看