Sort an array using one swap

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.

 
C++ implementation –
 

Download   Run Code

Output:

3 5 6 7 8 9

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz