Sort an array in one swap whose two elements are swapped by mistake

Given an array where all its elements are sorted except two elements which were swapped, sort the array in linear time. Assume there are no duplicates in the array.

For example,

Input:  A[] = [3, 8, 6, 7, 5, 9] OR [3, 5, 6, 9, 8, 7] OR [3, 5, 7, 6, 8, 9]

Output: A[] = [3, 5, 6, 7, 8, 9]

The idea is to start from the y element in the array and compare every element with its previous element. We take two pointers (say x and y) to store location of the conflict. If previous element is greater than the current element, we update x to the index of previous element and y to the index of current element. If again at some point we find that previous element is greater than the current element, we update y to index of current element. Finally, after we are done processing each adjacent pair of elements, we swap the elements present at index x and index y.

Output:

3 5 6 7 8 9

Java

Output:

[3, 5, 6, 7, 8, 9]

The time complexity of above solution is O(n) as it does only one scan of the input array and auxiliary space used by the program is O(1).

(1 votes, average: 5.00 out of 5)

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Subscribe
Notify of
Guest

This solution seems more efficient:

```public static void Main() { int[] a = {3,8,6,7,5,9}; int[] b = {3,5,6,9,8,7}; int[] c = {3,5,7,6,8,9}; Console.WriteLine(string.Join(",", sort(a))); Console.WriteLine(string.Join(",", sort(b))); Console.WriteLine(string.Join(",", sort(c))); }```

``` private static int[] sort(int[] array) { int left = 0, right = array.Length - 1; while (left < right) { Console.WriteLine("left = "+left+", right = " + right); // when it is pointed to the unordered pair that need to swap. if (array[right] < array[left]) { int temp = array[left]; array[left] = array[right]; array[right] = temp; break; } // move left if the adjacent to the right is less if(array[right] < array[right-1]) { left++; } // move right if the adjacent to the left is less else if(array[left] > array[left+1]) { right--; } // move both if the numbers adjacent are as expected. else { left++; right--; } } ```

``` return array; }```

The output of this is:

```left = 0, right = 5 left = 1, right = 4 3,5,6,7,8,9 left = 0, right = 5 left = 1, right = 5 left = 2, right = 5 left = 3, right = 5 3,5,6,7,8,9 left = 0, right = 5 left = 1, right = 4 left = 2, right = 3 3,5,6,7,8,9```