'How to get 2 numbers that swapping them make them correctly positioned
I have a problem with sorting. How can I get 2 numbers that when they swap they are both in the correct position? So I think for example about 3 and 4 because swapping them makes them at the correct position. I want to have a boolean variable that says if 2 swapped integers go to the right places it is true, else it is false. Basically for example if in loop we are at integer 4, we are checking his proposed index so it is (3). Then we use this index to see what is currently at this index in elephantsOrderGiven so it is 3. Then I want to check if 4 goes to the place of 3 will be correctly placed (so at index 3 in proposedOrder) and if 3 goes to the place of 4 will be correctly placed index(1 in proposedOrder). So it means 4 go to index (3), 3 goes to the index(1) and after swap they are both correct, so I want to have a boolean variable if swapping two integers will position them both correctly, because for example 5 and 2 will not be corrected positoned, only 2 will be.
let elephantsOrderGiven = [1, 4, 5, 3, 6, 2];
let proposedOrder = [5, 3, 2, 4, 6, 1];
for (let i = 0; i < elephantsOrderGiven.length; i++) {
}
Swapping I mean this operation:
temp = elephantsOrder[currentIndex];
elephantsOrder[currentIndex] = elephantsOrder[correctIndex];
elephantsOrder[correctIndex] = temp;
After this operation for example 4 and 3 should be corrected positoned like in proposed order. If not boolean variable should give False and the swapping should not be executed, I mean 4 and 3 should stay in their current positions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
