Sunday, 4 October 2015

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?
Example
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.
We strongly recommend to minimize your browser and try this yourself first.
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 C++ implementation of above idea.
// C program to sort using one swap
#include<iostream>
#include<algorithm>
using namespace std;
 
// This function sorts an array that can be sorted
// by single swap
void sortByOneSwap(int arr[], int n)
{
    // Travers the given array from rightmost side
    for (int i = n-1; i > 0; i--)
    {
        // Check if arr[i] is not in order
        if (arr[i] < arr[i-1])
        {
            // Find the other element to be
            // swapped with arr[i]
            int j = i-1;
            while (j>=0 && arr[i] < arr[j])
                j--;
 
            // Swap the pair
            swap(arr[i], arr[j+1]);
            break;
        }
    }
}
 
// A utility function ot print an array of size n
void printArray(int arr[], int n)
{
    int i;
    for (i=0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}
 
/* Driver program to test insertion sort */
int main()
{
    int arr[] = {10, 30, 20, 40, 50, 60, 70};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    cout << "Given array is \n";
    printArray(arr, n);
 
    sortByOneSwap(arr, n);
 
    cout << "Sorted array is \n";
    printArray(arr, n);
 
    return 0;
}
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.

No comments:

Post a Comment