Home > Enterprise >  Why this error of sorting occuring only in cases of >5 table elements?
Why this error of sorting occuring only in cases of >5 table elements?

Time:10-07

please see my code for BubbleSorting. When I choose 5 or more numbers for my table to be sorted I get an error: at first.firstt.sorting_v2.sorting(sorting_v2.java:35).

Completely do not know why it occured, when I choose 2 or three element to sort it works perfect. I know it can be made different way, this type of sorting but please show me what I did wrong as still learn and I'm very curious about the details of this error hmm.

Also see the image below:enter image description here

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Choose how much number you want to sort:");
        int sizeOfTab = scanner.nextInt();
        int[] numbers = new int[sizeOfTab];

        for (int i = 0; i < sizeOfTab; i  ) {
            System.out.println("Choose number to collection: ");
            numbers[i] = scanner.nextInt();
        }
        scanner.close();
        System.out.println(Arrays.toString(sorting(numbers)));
    }

    private static int[] sorting(int[] numbers) {
        boolean notDone = false;
        for (int i = 0; i < numbers.length - 1; i  ) {
            for (int j = 1; j < numbers.length; j  ) {
                if (numbers[i] > numbers[j]) {
                    int tmp = numbers[j];
                    numbers[j] = numbers[i];
                    numbers[i] = tmp;
                    notDone = true;
                }

            }

        }
        return notDone ? sorting(numbers) : numbers;
    }
}

CodePudding user response:

Your logical error is that you are always restarting your second inner loop from j = 1 aka the second element in

for (int j = 1; j < numbers.length; j  ) { ... }

You only ever want to compare numbers[i] > numbers[j] for cases where j is greater than i.

Lets say you have the array [1, 2, 3, 4]

Currently your loop will run and reach a point where it will check numbers[2] > numbers[1] and switch the second and third element despite the array already being sorted.

To fix this simply always have your second loop start from the current value of i with 1 added:

 for (int j = i 1; j < numbers.length; j  ) { ... }
  • Related