Skip to content
Advertisement

Difficulty trying to sort 10 numbers inputted by a user. Must use arrays and a separate method for sorting

My program isn’t sorting the numbers at all. It displays them in the order they were initially entered. It must sort them from smallest to largest number. The code below should find the largest number in the array and swap it with the last .the code is below:

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] + " ");
    }
}

Advertisement

Answer

I believe your problem is here:

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

array.length is not less than 0 so the for loop never runs. You probably wanted

for(int i=array.length-1; i>=0; i--)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement