Selection Sort

#include <iostream>

using namespace std;

void swap ( int &a, int &b )
{
    int temp = a;
    a = b;
    b = temp;
    return;
}

void printArr ( int arr[], int arrSize )
{
    for ( int i = 0; i < arrSize; i++ ) {
        cout << arr[i] << "   ";
    }
    cout << endl;
}

void selectionSort ( int arr[], int arrSize )
{
    int sortedIndex = 0;
    
    while ( sortedIndex < arrSize ) {
        int min = arr[sortedIndex];
        int minIndex = sortedIndex;
        for ( int i = sortedIndex + 1; i < arrSize; i++ ) {
            if ( arr[i] < min ) {
                min = arr[i];
                minIndex = i;
            }
        }
        swap(arr[minIndex], arr[sortedIndex]);
        cout << "iter " << sortedIndex << ": ";
        printArr(arr, arrSize);
        sortedIndex++;
    }
}

int main ( )
{
    cout << "Enter the size: ";
    int arrSize;
    cin >> arrSize;
    
    cout << "Enter the numbers\n";
    int arr[arrSize];
    for ( int i = 0; i < arrSize; i++ ) {
        cin >> arr[i];
    }
    
    selectionSort(arr, arrSize);
    
    cout << "--------Array sorted------\n";
    printArr(arr, arrSize);
    
    return 0;
}

selection sort image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s