Back to General discussions forum
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
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!
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
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.