You have been given an array 'ARR' of 'N' distinct elements.
Your task is to find the minimum no. of swaps required to sort the array.
For example:For the given input array [4, 3, 2, 1], the minimum no. of swaps required to sort the array is 2, i.e. swap index 0 with 3 and 1 with 2 to form the sorted array [1, 2, 3, 4].
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.
The first line of each test case contains an integer ‘N’ representing the size of the input array.
The second line of each test case contains the 'N' elements of the array separated by a single space.
Output Format:
For each test case, print a single line containing a single integer which represents the minimum no. of swaps required to sort the array.
The output for each test case is in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= N <= 1000
0 <= ARR[i] <= 10 ^ 9
Where 'ARR[i]' is the value of the input array elements.
Time Limit: 1 sec
2
4
4 3 2 1
5
1 5 4 3 2
2
2
For the first test case, swap index 0 with 3 i.e. 4 -> 1 and 1 with 2 i.e. 3 -> 2 to form the sorted array {1, 2, 3, 4}.
For the second test case, swap index 1 with 4 i.e. 5 -> 2 and 2 with 3 i.e. 4 -> 3 to form the sorted array {1, 2, 3, 4, 5}.
2
4
1 2 3 4
6
3 5 2 4 6 8
0
3
Swap every element of the given array with its right index, if it is not at the right place.
While iterating over the array, check the current element, and if not in the correct place, replace that element with the index of the element which should have come in this place.
Below is the algorithm:
O(N ^ 2), where ‘N’ is the size of the given array.
Since we are using indexOf() function to check the right index of every element of input array, having the worst case time complexity of O(N) for each array element. So, the overall complexity is O(N ^ 2).
O(N), where ‘N’ is the size of the given array.
Since we are using a temp array to store the sorted form of a given input array, thus, the space complexity will be O(N).