直接选择排序

直接选择排序

package com.ydlclass;

public class Test {
    public static void main(String[] args) {
     int[] a = {14,8,74,32};
      int index;//下标
        for (int i = 1; i < a.length; i++) {//i循环控制比较的轮数
            index = 0;//每轮下标为0
            for (int j = 1; j <= a.length-i; j++) {//j循环控制每轮数与数之间比较的次数,-i代表最后的数已经排列好不再对比
                if (a[index] > a[j]){//升序排列用大于号,降序排列用小于号
                    index = j;//交换下标
                }
            }
            int temp = a[a.length-i];//把最大的或最小的值换到本轮末尾
            a[a.length-i] = a[index];
            a[index] = temp;
        }
        System.out.println("直接选择排序结果:");
        for (int tmp: a) {
            System.out.print(tmp+"  ");
        }
    }
}

直接选择排序结果:
74  32  14  8  
Process finished with exit code 0
posted @ 2022-05-29 00:03  追风的羊  阅读(25)  评论(0)    收藏  举报