+ 1

Java code (Remove 0 to behind array)

Can anyone give me explanation of this code? https://code.sololearn.com/cpzwGj3PlUr9

9th Jun 2019, 8:28 AM
Tzion
Tzion - avatar
3 odpowiedzi
+ 3
It is like the bubble sort algorithm just with zeros. If a number is 0 swap it with its neighbour. That's what happens inside the second loop. 0 0 1 0 7 0 5 0 6 i = 0 j = 0 -> arr[0] = 0 -> swap arr[0] <-> arr[1] j = 1 -> arr[1] = 0 -> swap arr[1] <-> arr[2] ....until arr[l - 1] = 0 //last element after first iteration: 0 1 0 7 0 5 0 6 0 second iteration: 1 0 7 0 5 0 6 0 0 and so on...
9th Jun 2019, 9:34 AM
Denise Roßberg
Denise Roßberg - avatar
9th Jun 2019, 9:35 AM
Denise Roßberg
Denise Roßberg - avatar
+ 2
it search for 0 and if found some, shifts the 0 to the right it compares pairs and swaps it - in this way - again and again : (0 0) 1 0 7 0 5 0 6 swap(00) (0 0) 1 0 7 0 5 0 6 0 (0 1) 0 7 0 5 0 6 swap(01) 0 (1 0) 0 7 0 5 0 6 0 1 (0 0) 7 0 5 0 6 swap(00) 0 1 (0 0) 7 0 5 0 6 0 1 0 (0 7) 0 5 0 6 swap(07) 0 1 0 (7 0) 0 5 0 6 0 1 0 7 (0 0) 5 0 6 swap(00) 0 1 0 7 (0 0) 5 0 6 ... in the end, all zeros are on the right at the end of the array
9th Jun 2019, 9:57 AM
zemiak