+ 2
What is wrong with my else statements?
I am trying to get output only when loop is done or breaks when swapped == false. https://code.sololearn.com/cyXN2S7817n0/?ref=app
9 Respuestas
+ 3
Please specify what should the code do, expected outputs, your ways of approaching the issues you experience as well as describing those issues and a general explanation of the code.
+ 2
https://code.sololearn.com/ceEWGJhW9wy5/?ref=app
here I removed your syntax errors.
you put semicolon after else if that's your mistake and before else you used braces. still logical errors in your program
+ 1
Sorry but what you have not understand of
https://www.sololearn.com/discuss/1359298/?ref=app ? You have put "break" just soon inside an "if" statement that make it unuseful.. Futhermore there are some syntax errors. I said you to remove the condition (if(swapped==false)) but you dont want and make other question.... If you have a problem, try to resolve it before create others problems else you will have too problems to resolve and this will complicate all... You have understanded because i have said to remove your condition?
+ 1
KrOw, yes I did originally follow your suggestion. I think I got output after each iteration, and trying to fix I made code more problems.
+ 1
The reason I put break inside of if statement is to stop the loop when swapped == false because the loop would have served its purpose to put all elements in ascending order.
+ 1
First: Ident better your code
Second: Try to find YOURSELF the error/s on your code (above all if compiler tell you where and which is the error)
Third: If you cannot resolve it, post your problem BUT make your question clear and your code more readable
This is your code corrected (i think)
https://code.sololearn.com/cX9nCp11iTBp/?ref=app
+ 1
William Wilson A break statement inside an if statement just breaks out of the if statement and not the loop 😀
+ 1
i didn't clearly understand what you meant with the number of lines in output, but i made some changes to make it work properly :
static void bubbleSort(int[] arr) {
int temp;
int len = arr.length;
boolean swapped = true;
for(int i = 0; i < len-1; i++) {
swapped = false;
for(int j = 0; j < len-1; j++) {
if(arr[j]>arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = true;
}
}
if(swapped == false) {
System.out.print("BubbleSort: ");
for(int val : arr)
System.out.print(val + " ");
System.out.println();
break;
} else if (i == len-1){
System.out.print("BubbleSort: ");
for(int val : arr)
System.out.print(val + " ");
System.out.println();
}
}
}
+ 1
Good work IHeb04. Try running KrOW's version in above post. The code displayed output after each iteration in my version. KrOW got the code to display once after the sort was complete which was my intended result. I think you got the same result as KrOW. The code should display output integers in ascending order when inputs are originally in ascending order, descending order or mixed order.