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