I am trying to solve a problem:
You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates nor specific order.You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.
CONSTRAINTS:
- the number of elements must be >= 1
- the elements in the array must be <= to the size of the array
My code works when the numbers are not in the right position, but when the element is in the right position it enters an infinite loop, example array: [1 3 5 2 4 6 7]
<- My code doesn't work because it gets stuck on 1.
My code:
#include <iostream>
#include <vector>
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
int minimumSwaps(std::vector<int> arr)
{
int numberOfSwaps = 0;
int lastElementIndex = (arr.size() - 1);
bool isSwapping = true;
while (isSwapping)
{
isSwapping = false;
for (int i = 0; i < arr.size(); i++)
{
if (lastElementIndex - (arr.size() - arr[i]) != 0)
{
isSwapping = true;
swap(arr[i], arr[lastElementIndex - (arr.size() - arr[i])]);
numberOfSwaps++;
}
else
{
std::cout << arr[i] << " is already in its perfect position." << std::endl;
}
}
}
return numberOfSwaps;
}
P.S: I've just used the else statement to check what was going wrong.