Programming Examples

Cpp program to sort an array using selection sort


Write a program to sort an array using selection sort

Solution

#include<iostream>
using namespace std;
int main(){
    int arr[50],size,a,b,temp;
    cout<<" Enter the size of array";
    cin>>size;
    cout<<"Enter the elements in this array";
    for(a=0;a<size;a++)
    {
        cin>>arr[a];
    }
    for(a=0;a<size;a++)
    {
        int minIndex=a;
        for(b=a+1;b<size;b++)
        {
            if(arr[b]<arr[minIndex])
            {
                minIndex=b;
            }
        }
        temp=arr[a];
        arr[a]=arr[minIndex];
        arr[minIndex]=temp;
    }
    cout<<"After sorting :"<<endl;
     for(a=0;a<size;a++)
    {
        cout<<arr[a]<<" ";
    }
    return 0;
}
Output

Enter the size of array 10

Enter the elements in this array

90

45

23

91

1

2

6

45

78

13

After sorting :

1 2 6 13 23 45 45 78 90 91

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz