Bubble sort problem

Back to General discussions forum

Joao Meyer     2015-06-27 03:07:09

I don't know why this isn't working. Any ideas?

package beginner;

//Importing the scanner util
import java.util.Scanner;

public class BubbleSortCodeAbbey {

public static void main (String[] args) {

    //Scanning the total numbers in the first line
    Scanner scan = new Scanner (System.in);
    int total = scan.nextInt();

    //Declaring the array
    int[] array = new int[total];

    //For loop to set the values to the respective index in the array
    for (int i = 0; i < array.length; i++) {
        array[i] = scan.nextInt();
    }

    boolean end = false;
    int t;


    int passes = 0;
    int swaps = 0;

    while (!end) {

        //For loop to do all the passing trough the whole array
        for (int k = 0; k < array.length; k++) {

            //Sets the boolean to true, if the if statement don't works, will stop the counting of passes
            end = true;

            //Passing to check, it jumps the already checked indexes
            for (int j = 1; j < (array.length-k); j++) {

                if (array[j-1] > array[j]) {

                    //Sets the boolean to false, so it will keep counting
                    end = false;

                    //Swaping the elements
                    t = array[j-1];
                    array[j-1] = array[j];
                    array[j] = t;

                    swaps++;
                }
            }

            passes++;
        }
    }

    //Prints the number of swaps and passes
    System.out.print(passes + " " + swaps);
}
}

Input: 23 5 16 15 3 7 17 18 8 11 22 21 23 19 10 13 4 9 1 14 20 2 6 12

Output I get: 23 134

Correct output: 20 134

Rodionische     2015-06-27 06:53:44
User avatar

Hi! Thanks for your message!

It looks like your trick with end does not work, though your intention is correct. So you always make the full amount of passes (equal to N). I believe you can debug and fix it, but feel free to write for more explanations if you still have troubles!

Joao Meyer     2015-06-27 13:41:13

I fixed it! I just removed the first for loop. I think I was trying to make it more efficient and was doing things I didn't knowh. Haha

Dominic     2017-03-28 19:45:32

This took me so god damn long to figure out.

Dont forget to also count the number of times you don't have to swap i.e the number of perfect passes is always going to be a certain number.

Until the count reaches that number just keep looping.

Please login and solve 5 problems to be able to post at forum