+ 3
Sort Numbers in Java
I would like to write a code to sort numbers in ascending order. But there is something wrong with this code? Why 1 cannot be sort? Thanks https://code.sololearn.com/c91S59ES624u/?ref=app
3 odpowiedzi
+ 6
It looks like problem is 1 is not sorted, actual problem is not because it is 1.
Because you just swap two adjacents position once
You need to keep swapping them until all numbers is at right position
Use another loop called for j inside for i
See explanation of Bubble Sort on Sololearn lesson:
https://www.sololearn.com/learn/649/?ref=app
In other words, for sorting n numbers, you need to do n*n times of comparison for Bubble Sort
+ 2
I just checked this demo about Bubble Sort, a better way is create a flag called swapped and use do while loop. Can stop the sorting earlier when sorting is done detected.
https://code.sololearn.com/WRK8Y6Bkj9eP/?ref=app
+ 2
You have to iterate throu the Array until you havent swaped values.
Here a solution in Java:
boolean swaped = false;
do {
swaped = false;
for (int i = 0; i < a.length - 1; i++) {
if(a[i] > a[i+1]) {
int temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swaped=true;
}
}
} while (swaped);
Hope, that helps ;-)