Here is my problem statement. An excerpt:
You are given an unordered array consisting of consecutive integers
∈ [1, 2, 3, ..., n]
without any duplicates. 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.For example, given the array
arr = [7, 1, 3, 2, 4, 5, 6]
we perform the following steps:
i arr swap (indices)
0 [7, 1, 3, 2, 4, 5, 6] swap (0,3)
1 [2, 1, 3, 7, 4, 5, 6] swap (0,1)
2 [1, 2, 3, 7, 4, 5, 6] swap (3,4)
3 [1, 2, 3, 4, 7, 5, 6] swap (4,5)
4 [1, 2, 3, 4, 5, 7, 6] swap (5,6)
5 [1, 2, 3, 4, 5, 6, 7]
It took 5 swaps to sort the array.
The code:
int minimumSwaps(int arr_count, int* arr) {
long long int i,count=0,j,temp,min,min_index;
for(i=0;i<arr_count;i++)
{
min=arr[i];
min_index=i;
for(j=i+1;j<arr_count;j++)
{
if(arr[j]<min)
{
min=arr[j];
min_index=j;
}
}
if(min_index!=i)
{
count++;
temp=arr[min_index];
arr[min_index]=arr[i];
arr[i]=temp;
}
}
return count;
}
5 out of 15 test-cases are failing. Here is one of the test cases. It is failing with a message as "Terminated due to timeout".
I used selection sort approach as selection sort makes minimum swap operation. My time complexity is O(n^2). Can I reduce it?
int
. It doesn't make any sense to uselong long int
for all local variables; that will just slow down your implementation, which is already a \$O(n^2)\$ slow algorithm. The optimal solution will scale slower than \$O(n^2)\$. \$\endgroup\$