Sort an almost sorted array where only two elements are swapped
Sort an almost sorted array where only two elements are swapped
Given an almost sorted array where only two elements are swapped, how to sort the array efficiently?
Examples :
Input: arr[] = {10, 20, 60, 40, 50, 30} // 30 and 60 are swapped Output: arr[] = {10, 20, 30, 40, 50, 60} Input: arr[] = {10, 20, 40, 30, 50, 60} // 30 and 40 are swapped Output: arr[] = {10, 20, 30, 40, 50, 60} Input: arr[] = {1, 5, 3} // 3 and 5 are swapped Output: arr[] = {1, 3, 5}
Expected time complexity is O(n) and only one swap operation to fix the array.
The idea is to traverse from rightmost side and find the first out of order element (element which is smaller than previous element). Once first element is found, find the other our of order element by traversing the array toward left side.
Below is implementation of above idea.
Output :
Given array is 10 30 20 40 50 60 70 Sorted array is 10 20 30 40 50 60 70
The above program works in O(n) time and swaps only one element.
Comments
Post a Comment