C and C++

Program to sort a given array using selection sort

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:

  1. Start with the first element (index 0) as the minimum.

  2. Compare it with every element in the unsorted part of the array to find the smallest value.

  3. Swap the smallest value with the current element.

  4. Move to the next index and repeat until the array is sorted.


Example:
Suppose we have the array:

[29, 10, 14, 37, 13]

Step-by-step:

  1. Pass 1: Smallest element in [29, 10, 14, 37, 13] is 10 → Swap with 29[10, 29, 14, 37, 13]

  2. Pass 2: Smallest in [29, 14, 37, 13] is 13 → Swap with 29[10, 13, 14, 37, 29]

  3. Pass 3: Smallest in [14, 37, 29] is 14 → No swap needed → [10, 13, 14, 37, 29]

  4. Pass 4: Smallest in [37, 29] is 29 → Swap with 37[10, 13, 14, 29, 37]

  5. 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

Leave a comment

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