0
What is the logic behind i=-1
So I saw this single loop sort algorithm method and I was wondering the logic behind the line i=-1.The array only gets sorted when he does that .How did he know that is what was required,any theory behind it? https://code.sololearn.com/WmdjiruHbI8n/?ref=app
5 Answers
+ 1
The loop goes over ther whole array multiple time. After doing a value swap, the array is being validated again.
Remember that i gets incremented at each loop because of the i++, setting i to -1, then increment it with i++, you are now back at 0!
1 3 2
^ ^ 1 > 3: false
1 3 2
^ ^ 3 > 2: true, swap them
restart ( i = -1)
1 2 3
^ ^ 1 > 2: false
1 2 3
^ ^ 2 > 3: false
all good
I hope this helps :)
+ 1
Looks like a recursive loop.
Setting i = -1 after a swap forces the iteration to start from the beginning, so that the comparison and swap is made repeatedly. This way, the entire list is sorted, and the previous values are rechecked.
+ 1
i = -1 cancels out the i++.
it forces the iteration to start from the beginning.
Since we are only swapping two values at a time, the previously swapped values might need to be swapped again. That's why it needs to go back to the starting point.
0
Still confused Apollo-Roboto ,considering that the original loop starts at 0.if one part is sorted ,shouldn't that be incrementing to the unsorted part?..why go back to -1
0
Ok Bob_Li thanks a lot I never knew this Apollo-Roboto thanks too .you both seem to be saying the same thing..I'll read up on it.