Program to sort a given array using selection sort
Selection sort works by repeatedly finding the smallest (or largest) element from the unsorted part of the array and putting it in its correct position in the sorted part.
Steps:
-
Start with the first element (index
0) as the minimum. -
Compare it with every element in the unsorted part of the array to find the smallest value.
-
Swap the smallest value with the current element.
-
Move to the next index and repeat until the array is sorted.
Example:
Suppose we have the array:
Step-by-step:
-
Pass 1: Smallest element in
[29, 10, 14, 37, 13]is10→ Swap with29→[10, 29, 14, 37, 13] -
Pass 2: Smallest in
[29, 14, 37, 13]is13→ Swap with29→[10, 13, 14, 37, 29] -
Pass 3: Smallest in
[14, 37, 29]is14→ No swap needed →[10, 13, 14, 37, 29] -
Pass 4: Smallest in
[37, 29]is29→ Swap with37→[10, 13, 14, 29, 37] -
Sorted!
#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);
}
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


