Minimum Swaps Two HackerRank Solution in Java
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.
See full description in HackerRank Website :-
public class MinimumSwaps2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size");
int arraySize = sc.nextInt();
int array[] = new int[arraySize];
System.out.println("Enter array values ");
for (int i = 0; i < arraySize; i++) {
array[i] = sc.nextInt();
}
int totalSwap = 0;
// Loop through loop
for (int i = 0; i < array.length; i++) {
// Check if array index and value are matched or not
if (array[i] != i+1) {
int index = i;
// Loop until index not matched array value
while (array[index] != i+1) {
index++;
}
// Swap array value with finded value
int temp = array[index];
array[index] = array[i];
array[i] = temp;
totalSwap++;
}
}
System.out.println(totalSwap);
}
}
Output :-
Enter array size
5
Enter array values
2 3 4 1 5
Total Swaps: 3
---------------------
Enter array size
7
Enter array values
1 3 5 2 4 6 7
Total Swaps: 3
Explanation :-
- First loop through array and check if array value is matching with index or not (like index 1 is match with array value 1) if it matches then we don't need to swap the value.
- If it array index does not match with array value then goes into while loop.
- Checking which array index contains current index value
- After matching swap the values and increment the totalSwap variable.
Example :-
4
4 3 1 2
1 3 4 2 (Swap 4 and 1)
1 2 4 3 (Swap 2 and 3)
1 2 3 4 (Swap 3 and 4)
If you have still doubt in above explanation comment down. Thank You.
Other HackerRank Problems and Solutions :-
Comments
Post a Comment