第七章第二十题(修改选择排序法)(Modify the selection sorting method)

第七章第二十题(修改选择排序法)(Modify the selection sorting method)

  • *7.20(修改选择排序法)在7.11节中, 使用了选择排序法对数组排序。选择排序法重复的在当前数组中找到最小值,然后将这个最小值与该数组中的第一个数进行交换。改写这个程序,重复的在当前数组中找到最大值,然后将这个最大值与该数组中的最后一个数进行交换。编写一个测试程序,读取10个double型的数字,调用该方法,并显示排好序的数字。
    *7.20(Modify the selection sorting method)In section 7.11, select sort is used to sort the array. The sorting method repeatedly finds the minimum value in the current array, and then exchanges the minimum value with the first number in the array. Rewrite this program, repeatedly find the maximum value in the current array, and then exchange the maximum value with the last number in the array. Write a test program, read 10 double type numbers, call the method, and display the ordered number.

  • 参考代码:

    package chapter07;
    
    import java.util.Scanner;
    
    public class Code_20 {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            System.out.print("Enter 10 doubles: ");
            double[] str = new double[10];
            for(int i = 0;i < 10;i++)
                str[i] = input.nextDouble();
            selectionSort(str);
            for(int i = 0;i < 10;i++)
                System.out.print(str[i] + " ");
        }
        public static void selectionSort(double[] list){
            for(int i = 0;i < list.length - 1;i++){
                double currentMax = list[i];
                int currentMaxIndex = i;
                for(int j = i + 1;j < list.length;j++){
                    if(currentMax > list[j]){
                        currentMax = list[j];
                        currentMaxIndex = j;
                    }
                }
                if(currentMaxIndex != i){
                    list[currentMaxIndex] = list[i];
                    list[i] = currentMax;
                }
            }
        }
    }
    
    
  • 结果显示:

    Enter 10 doubles: 3 4 5 6 7 2 1 0 10 22
    0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 10.0 22.0 
    Process finished with exit code 0
    
    
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值