Minimum Swaps 2
2 min readAug 31, 2023
Problem Statement
You are given an unordered slice consisting of consecutive integers [3 6 1 7 2 9]
without any duplicates. Find the minimum number of swaps required to sort the slice in ascending order.
Problem Considerations
It is in fact another sorting problem, we are given an slice and being tell to sort it in ascending order using the less swaps possible.
Let’s start with a naive but pragmatic approach, looping over the slice and swapping value each time an element is in wrong position.
The algorithm
- The function first creates a slice of pairs
slicePairs
to store the element alongside their current index. This is done using thesliceMap
function, which takes a projection function as input. The projection function in this case iselementIndexPair
, which takes the index and the element of the slice and returns a structeIndexPairs
with the index and element as its fields. - The
slicePairs
slice is then sorted in ascending order using thesort
package. - Next, a boolean array
visited
is created to keep track of the visited positions in the slice - The function then iterates over the
slicePairs
slice. For each element in the slice, the following steps are performed:
- If the element has already been visited or is at the correct position, the function continues to the next element.
- Otherwise, the function starts a cycle.
- The function iterates over the cycle, swapping the elements at the current position and the element’s index.
- The function marks the current position as visited.
- The size of the cycle is incremented.
- The function breaks out of the cycle when the current position is equal to the element’s index.
5. The function then increments the swaps
variable by the size of the cycle.
6. Finally, the function returns the value of the swaps
variable.