'understanding sorting an array
I'm having trouble understanding the sorting that occurs in the last if statement block. Can someone please explain how it works or useful resources i could refer to? I posted a screenshot of the source code for reference. enter image description here
if (currentIndex != i) {
temp = array[i];
array[i] = array[currentIndex];
array[currentIndex] = temp;
arr[currentIndex] = arr[i];
arr[i] = currentIndex;}
Solution 1:[1]
You don't really need that if statement. currentIndex (which starts at i) defines what the current position of the maximum value we haven seen is. Of course, if the value that you initially chose (at position i) is the maximum value, then in the inner for loop (with j) would never change the value of currentMax and currentIndex. The if statement is just saying if the value that is already at i is the maximum value (meaning currentIndex never changes), then there is no point in swapping the value at i and currentIndex because they are the same position.
For example, take the following values:
10, 8, 3, 2, 6
Let's say we have already placed 10 into the correct position (as the greatest value, that would be the first value you find and put into the correct position). Then, the for loop with i would move to the next value (position 1). So you set currentMax and currentIndex to the following:
currentMax = 8
currentIndex = 1
At which point you move onto the inner for loop with j. Starting at i + 1 (or 2 in this case), you check all of the values to the right of your currentIndex to see if there's any value greater than currentMax. Since you don't see any, then currentMax doesn't change (so it stays at 8), which also means currentIndex doesn't change (stays at 1).
So we come to the if statement. We know that:
currentIndex = 1
i = 1
Since the currentIndex and i equal each other, there is no point in swapping the values because they are the same values. Of course, you don't really need that if statement since swapping a value with itself doesn't really affect anything.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | charlie-map |
