A sorting algorithm that slightly improves on selection sort

3

As we know, selection sort algorithm takes the minimum on every pass on the array, and place it at its correct position.

The idea is to take also the maximum on every pass and place it at its correct position. So in every pass, we keep track of both maximum and minimum and array becomes sorted from both ends.

Examples:

First example: 7 8 5 4 9 2 
Input :pass 1:|7 8 5 4 9 2| 
       pass 2: 2|8 5 4 7|9
       pass 3: 2 4|5 7|8 9       
Output :A sorted array:  2 4 5 7 8 9

second example: 23 78 45 8 32 56 1      
Input :pass 1:|23 78 45 8 32 56 1|
       pass 2: 1|23 45 8 32 56 |78
       pass 3: 1 8|45 23 32|56 78
       pass 4: 1 8 23 |32|45 56 78
       in a case of odd elements, so one element
       left for sorting, so sorting stops and the
       array is sorted.
Output : A sorted array: 1 8 23 32 45 56 78
// C++ program to implement min max selection
// sort.
#include <iostream>
using namespace std;

void minMaxSelectionSort(int* arr, int n)
{
    for (int i = 0, j = n - 1; i < j; i++, j--) {
        int min = arr[i], max = arr[i];
        int min_i = i, max_i = i;
        for (int k = i; k <= j; k++)  {
            if (arr[k] > max) {
                max = arr[k];
                max_i = k;
            } else if (arr[k] < min) {
                min = arr[k];
                min_i = k;
            }
        }

        // shifting the min.
        swap(arr[i], arr[min_i]);

        // Shifting the max. The equal condition
        // happens if we shifted the max to arr[min_i] 
        // in the previous swap.
        if (arr[min_i] == max) 
            swap(arr[j], arr[min_i]);
        else
            swap(arr[j], arr[max_i]);
    }
}

// Driver code
int main()
{
    int arr[] = { 23, 78, 45, 8, 32, 56, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    minMaxSelectionSort(arr, n);
    printf("Sorted array:\n");
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
    return 0;
}

Output:

 Sorted array: 1 8 23 32 45 56 78

This article is contributed by Shlomi Elhaiani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



3 Average Difficulty : 3/5.0
Based on 1 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.