Selection sort algorithm in C++

Selection sort algorithm

        The algorithm has two loops one for iteration and the other for comparing. And two variables one(min variable) to store the smallest element and the other(index variable) to store its index. 

        Assign the first element of the array to the min variable and the index variable to zero.

        Start the second loop from the i+1th index and check whether any element is smaller than the current min element if so assign that element to min and its index to the index variable.

        Once the second loop is executed swap the min element with the ith element.

        After the complete execution of the main loop, the array will be sorted. Print the array!

Code

#include <bits/stdc++.h>

using namespace std;


int main() {

    int a[5]={500,3,45,999,78};                //array

    

    for(int i=0;i<4;i++)                // always iterate the loop till one less than the size 

    {     

        int min=a[i];                        // to store minimum element

        int g=0;                                // to store index value

        

        for(int j=i+1;j<5;j++)                    //main loop

        {

            if(a[j]<min)                                    //if any smaller element encountered update min and g

            {

            min=a[j]; 

                    g=j;

    }

        }

        

        int t=a[i];                 //

        a[i]=min;               // swapping section 

        a[g]=t;                 // 

    }

    

    for(int i=0;i<5;i++)                        //print the array

    {

        cout<<a[i]<<" ";

    } 

    

    return 0;

}



Output

3 45 78 500 999

Post a Comment

0 Comments