【问题标题】:Difficulty trying to sort 10 numbers inputted by a user. Must use arrays and a separate method for sorting难以对用户输入的 10 个数字进行排序。必须使用数组和单独的方法进行排序
【发布时间】:2021-07-26 20:55:15
【问题描述】:

我的程序根本没有对数字进行排序。它按照最初输入的顺序显示它们。它必须从最小到最大对它们进行排序。下面的代码应该找到数组中最大的数字,并与最后一个交换。代码如下:

import java.util.Scanner;

public class maxSorttt {

    public static void main(String[] args) {

        double[] ten = new double[10];
        Scanner input = new Scanner(System.in);
        System.out.print("Enter 10 numbers: ");
        for (int i = 0; i < ten.length; i++)
            ten[i] = input.nextDouble();

        sort(ten);

    }

    public static void sort(double[] array) {
        for (int i = array.length - 1; i < 0; i--) {
            double currentMax = array[i];
            int currentMaxIndex = i;

            for (int x = i - 1; x < -1; x--) {    
                if (currentMax < array[x]) {    
                    currentMax = array[x];
                    currentMaxIndex = x;
                }
            }

            if (currentMaxIndex != i) {
                array[currentMaxIndex] = array[i];
                array[i] = currentMax;
            }
        }


        for (int i = 0; i < array.length; i++)
            System.out.print(array[i] + " ");
    }
}

【问题讨论】:

  • 谢谢bschellekens!你的答案有效。我很困惑。我希望循环在小于 0 时停止,所以是的 i>=0 是正确的。

标签: java arrays sorting swap


【解决方案1】:

我相信你的问题就在这里:

for(int i=array.length-1; i<0; i--)

array.length 不小于 0,因此 for 循环永远不会运行。你可能想要

for(int i=array.length-1; i>=0; i--)

【讨论】:

    【解决方案2】:

    要简单!

    public static void selectionSort(double[] arr) {
        for (int i = 0; i + 1 < arr.length; i++) {
            int minIndex = findMinIndex(arr, i + 1);
    
            if (Double.compare(arr[i], arr[minIndex]) > 0)
                swap(arr, i, minIndex);
        }
    }
    
    private static int findMinIndex(double[] arr, int i) {
        int minIndex = i;
    
        for (; i < arr.length; i++)
            if (Double.compare(arr[i], arr[minIndex]) < 0)
                minIndex = i;
    
        return minIndex;
    }
    
    private static void swap(double[] arr, int i, int j) {
        double tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-11
      • 2022-01-17
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多