+ 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.

10th Jun 2020, 8:14 AM
Radu Weisz
Radu Weisz - avatar
8 Respuestas
+ 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");
10th Jun 2020, 12:49 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
Ok, thanks! I'll try this. 👍👍
10th Jun 2020, 1:05 PM
Radu Weisz
Radu Weisz - avatar
+ 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; } }} }
10th Jun 2020, 4:45 PM
zemiak
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
10th Jun 2020, 10:38 AM
zemiak
0
Ok, thanks a lot! Now i understeand the algorithm, but i wondered if u could explain me the code...
10th Jun 2020, 10:47 AM
Radu Weisz
Radu Weisz - avatar
10th Jun 2020, 10:49 AM
Radu Weisz
Radu Weisz - avatar
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!
10th Jun 2020, 4:54 PM
Radu Weisz
Radu Weisz - avatar
11th Jun 2020, 4:52 PM
A S Raghuvanshi
A S Raghuvanshi - avatar