选择排序

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

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 ("\n");

        }


    }

    public static void main(String[] args) {

        int [] shuzu = new int[SIZE];


        shuzu[0] = 25;
        shuzu[1] = 29;
        shuzu[2] = 21;


        System.out.print ("排序前的数组为:\n");

        for (int j = 0; j < 3; j++) {

            System.out.print(shuzu[j]+ " ");

        }

        System.out.println ();

        selectSort (shuzu);

        System.out.print ("排序后数组为:\n");


        for (int j = 0; j < 3; j++) {

            System.out.print(shuzu[j]+ " ");

        }


        System.out.print("\n");



    }

}

posted @ 2021-03-04 14:24  yongjar  阅读(45)  评论(0编辑  收藏  举报