Saturday, August 18, 2018

Minimum Swaps 2

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  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  swaps to sort the array.
Solution :- 
static int minimumSwaps(int[] arr)
        {
            var sortedArr = arr.OrderBy(x => x).ToArray();
            var count = 0;
            var unsortedArr = arr;
            int temp;
            for (int i = 0; i < sortedArr.Length; i++)
            {
                if (sortedArr[i] != unsortedArr[i])
                {
                    count++;
                    for (int j = i+1; j < unsortedArr.Length; j++)
                    {
                        if (unsortedArr[j] == sortedArr[i])
                        {
                            temp = unsortedArr[j];
                            unsortedArr[j] = unsortedArr[i];
                            unsortedArr[i] = temp;
                           
                            break;
                        }
                    }
                }
            }
            return count;
        }



No comments:

Post a Comment

Exploring dijkstra algorithm explain with solved example

Unraveling the Dijkstra Algorithm: A Solved Example Unraveling the Dijkstra Algorithm: A Solved Example Introductio...