• 选择排序


    具体的执行步骤请详细看注释!!!

    package com.yongjar.test;
    
    /**
     * @author yongjar
     * @date 2021/3/1
     * 选择排序
     * 选择排序算法在每一步中选取最小值来重新排列,从而达到排序的目的。
     */
    public class P4_2 {
    
        static final int SIZE =3;
    
        public static void selectSort(int [] a) {
    
    
            int index,temp;
            // i=0; a<3-1;
            // i++ = 1; a<3-1;
            for (int i = 0; i < a.length-1; i++) {
    
                // index = 0;
                // index = 1;
                index = i;
                //j=0+1 j<3 true
                //j=2  j<3 true
                for (int j = i+1; j < a.length; j++) {
    
                    // a[1](29) < a[0](25) false 继续for循环
                    // a[2](21) < a[0](25) true
                    //a[2](25) < a[1](29) true
                    if (a[j] < a[index]) {
                        //index = 2;
                        // index = 2;
                        index = j;
                    }
    
                }
    
                //  2 != 0
                // 2 !=1
                if (index != i) {
                    // temp = a[0](25)
                    // temp = a[1](29)
                    temp = a[i];
                    //a[0] = a[2](21)
                    // a[1] = a[2](25)
                    a[i] = a[index];
                    //a[2] = temp(25)
                    //a[2] = temp(29)
                    a[index] = temp;
                }
    
                System.out.println ("第"+i+"排序结果是:");
                for (int j = 0; j <a.length ; j++) {
                    System.out.print (" " + a[j]);
                }
    
                System.out.println ("
    ");
    
            }
    
    
        }
    
        public static void main(String[] args) {
    
            int [] shuzu = new int[SIZE];
    
    
            shuzu[0] = 25;
            shuzu[1] = 29;
            shuzu[2] = 21;
    
    
            System.out.print ("排序前的数组为:
    ");
    
            for (int j = 0; j < 3; j++) {
    
                System.out.print(shuzu[j]+ " ");
    
            }
    
            System.out.println ();
    
            selectSort (shuzu);
    
            System.out.print ("排序后数组为:
    ");
    
    
            for (int j = 0; j < 3; j++) {
    
                System.out.print(shuzu[j]+ " ");
    
            }
    
    
            System.out.print("
    ");
    
    
    
        }
    
    }
    
    
  • 相关阅读:
    BZOJ1042: [HAOI2008]硬币购物
    BZOJ1089: [SCOI2003]严格n元树
    BZOJ1060: [ZJOI2007]时态同步
    BZOJ2697: 特技飞行
    BZOJ2464: 中山市选[2009]小明的游戏
    BZOJ1430: 小猴打架
    BZOJ3675: [Apio2014]序列分割
    BZOJ2453: 维护队列
    BZOJ2120: 数颜色
    BZOJ4547: Hdu5171 小奇的集合
  • 原文地址:https://www.cnblogs.com/jamal/p/14480057.html
Copyright © 2020-2023  润新知