VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-an-almost-sorted-array-where-only-two-elements-are-swapped/

⇱ Sort an almost sorted array where only two elements are swapped - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort an almost sorted array where only two elements are swapped

Last Updated : 23 May, 2022

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 out 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

Time Complexity: O(N), as we are using a loop to traverse the array.

Auxiliary Space: O(1), as we are not using extra space.
The above program works in O(n) time and swaps only one element.
 

Comment
Article Tags:
Article Tags: