Selection Sort in C++

This program, implements the selection sort in C++ language.
Here is the source code of the C++ program which takes the values of array as input and returns the sorted array as output. This C++ program is successfully compiled and run on DevCpp, a C++ compiler. The program output is also shown below.
selection sort in  c

 Selection sort animation.             —->>>

Red is current min. Yellow is sorted list. Blue is current item. 
source: wikipedia

PROGRAM:

/*
 * C++ Program to Implement Selection Sort
 */
#include<stdio.h>
#include<iostream>
using namespace std;

int main()
{
    int lowindex,lowkey,temp,n;
    cout<<"enter the number of valuesn";
    cin>>n;
    int a[n];
    cout<<"enter values of arrayn";
    for (int i = 0; i < n; i++)
    {
        cin>>a[i];
    }
    for (int i = 0; i <= n - 1; i++)
    {
        lowindex = i;
        lowkey = a[i];
        for (int j = i + 1; j <= n; j++)
        {
            if (a[j] < lowkey)
            {
                lowkey = a[j];
                lowindex = j;
            }
        }
        temp = a[i];
        a[i] = a[lowindex];
        a[lowindex] = temp;
    }
    cout<<"After sortingn";
    for (int k = 0; k < n; k++)
    {
        cout<<a[k]<<endl;
    }
    return 0;
}

 

OUTPUT:

enter the number of values
7
enter values of array
32
56
16
9
5
12
75
After sorting
5
9
12
16
32
56
75

 

Leave a Reply