C and C++

Program to sort a given array using selection sort

Program to sort a given array using selection sort
#include<iostream.h>
main()
{
int n, a[20], i,j,small, pos;
cout<<"Enter the size of an array:"; cin>>n;
cout<<"Enter the elements to array:\n";
for(i=0; i<n; i++) cin>>a[i];
cout<<"\n\n Elements before sorting:\n";
for(i=0; i<n; i++)
cout<<a[i]<<"\t";
for(i=0; i<n-1; i++)
{
small = a[i];
pos = i;
for(j=i+1; j<n; j++) { if(small > a[j])
{
small = a[j];
pos = j;
}
}
a[pos] = a[j];
a[i] = small;
}
cout<<"\n\n Elements after sorting:\n";
for(i=0; i<n; i++)
cout<<a[i]<<"\t";
cout<<endl;
return(0);
}

[wp_ad_camp_1]

OUTPUT
Enter the size of an array: 5
Enter the elements to array:
3
2
9
7
6
Elements before sorting:
3 2 9 7 6
Elements after sorting:
2 3 6 7 9

Leave a comment

Your email address will not be published. Required fields are marked *