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

    思路

      默认从小到大排序

    1. 角标0跟后面的所有的对比,如果前面比后面大,交换位置
    2. 之后角标1跟后面对比,如果前面比后面打,交换位置
    3. 以此类推
    4. 内循环结束,则最小的放在了角标0

    代码

    /**
     * Created by binfoo on 2016/7/10.
     */
    public class SelectSort {
    
        /**
         * 选择排序
         */
        public static void selectSort(int[] arr) {
    
            for(int i = 0; i < arr.length - 1 ;i++){
                for(int j = i+1;j<arr.length;j++){
    
                    if(arr[i]>arr[j]){
                        int temp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
    
        }
        public static void printArray(int[] arr){
            System.out.print("[ ");
            for (int i = 0 ;i < arr.length  ;i++){
    
                if(i < arr.length -1){
                System.out.print(arr[i]+ ",");}
                else {
                    System.out.print(arr[i]+" ]");
                }
            }
        }
    
        public static void main(String[] args){
            int[] arr = {2,43,55,5,22,33,88,1,0};
            System.out.println("Before sort : ");
            printArray(arr);
            selectSort(arr);
            System.out.println("
    After sort : ");
            printArray(arr);
    
        }
    }

    验证

     

    Before sort :
    [ 2,43,55,5,22,33,88,1,0 ]
    After sort :
    [ 0,1,2,5,22,33,43,55,88 ]
    Process finished with exit code 0

  • 相关阅读:
    POJ1942-Paths on a Grid
    CodeForces 245C-Game with Coins
    codeforces 244B-Undoubtedly Lucky Numbers 搜索
    URAL
    HDU-1134 卡特兰数+java大数模板
    素数线性筛
    KMP讲解
    bzoj 3143: [Hnoi2013]游走
    bzoj 3238: [Ahoi2013]差异
    bzoj 2208: [Jsoi2010]连通数
  • 原文地址:https://www.cnblogs.com/binfoo/p/5657993.html
Copyright © 2011-2022 走看看