选择排序

/**

  • 选择排序

  • 1.将maxIndex赋值为数组第一个元素的索引

  • 2.与下一个值分别做比较,若小于下一个值则将较大值的索引赋值给maxIndex

  • 3.比较结束后将最大值置于最后,将maxIndex重新赋值为0

  • 4.下一轮比较开始
    */
    public class CollectionDemo1 {
    public static void main(String[] args) {
    int[] nums = {1, 4, 3, 5, 2};

     int maxIndex = 0;
     int temp = 0;
     int lastIndex = nums.length - 1;
    
     for (int i = nums.length - 1; i > 0; i--) {//一共比较几轮
         for (int j = 1; j < i + 1; j++){//首个元素不用和自身比较
             if(nums[maxIndex] < nums[j]){
                 maxIndex = j;
             }
         }
         //循环结束后得到maxIndex为第一轮比较的最大元素的索引,将最大索引处的元素与最后一个值交换
         temp = nums[maxIndex];
         nums[maxIndex] = nums[lastIndex];
         nums[lastIndex] = temp;
         lastIndex--;
         maxIndex = 0;//maxIndex初始化
     }
     for (int i = 0; i < nums.length; i++) {
         System.out.print(nums[i] + " ");
     }
    

    }
    }

posted @ 2022-11-19 11:37  都是废话说了  阅读(25)  评论(0)    收藏  举报