+ 1
Can someone explain me the bubble sort in java?
Hi! I've tried a lot to understeand the bubble sort in java. I searched on the internet or just with a piece of paper and a pen, but I just couldn't understeand it. I hope you can help me, or suggest me a website where the sort is explained step by step.
8 odpowiedzi
+ 3
Well, it just does exactly this - compares and switches places of the item and the one next to it, until there are no more to switch...
https://www.sololearn.com/learn/649/?ref=app
I suggest you add a print line for each iteration, to see it step by step.
Add as lines 13-14:
printArray(arr);
System.out.print("\n");
+ 1
Ok, thanks! I'll try this. 👍👍
+ 1
static void bubbleSort(int[] arr) {
// how many times check line again
for(int i=0; i<arr.length-1; i++) {
// check line, j is position of compared numbers
for(int j=0; j<arr.length-1; j++) {
// compare two numbers
if(arr[j] > arr[j+1]) {
//swap:
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
} }} }
0
2 5 4 6 1 3
(2 5)4 6 1 3
2(5 4)6 1 3 swap 5 4
2 4(5 6)1 3
2 4 5(6 1)3 swap 6 1
2 4 5 1(6 3) swap 6 3
2 4 5 1 3 6 (6 at right place)
again
(2 4)5 1 3
2(4 5)1 3
2 4(5 1)3 swap 5 1
2 4 1(5 3) swap 5 3
2 4 1 3 5 (5 6 ok)
(2 4)1 3
2(4 1)3 swap 4 1
2 1(4 3) swap 4 3
2 1 3 4 (4 5 6 ok)
(2 1)3 swap 2 1
1(2 3)
(1 2) (all array ok)
1 2 3 4 5 6 result
0
Ok, thanks a lot! Now i understeand the algorithm, but i wondered if u could explain me the code...
0
Due to your suggestions i finally understood it...thanks for your support. I think this disscusion part is the best choice for people that want to get some answers for their problems. I love Solo learn!
0
This post will help you
https://www.tutorialspoint.com/java-program-to-implement-bubble-sort