Selection Sort
SELECTION SORT IN C
We start Selection Sort by scanning the entire given list to find its smallest element and exchange it with the first element, putting the smallest element in its final position in the sorted list. Then we scan the list, starting with the second element, to find the smallest among the last n - 1 elements and exchange it with the second element, putting the second smallest element in its final position. Generally, on the ith pass through the list, which we number from 0 to n - 2, the algorithm searches for the smallest item among the last n - i elements and swaps it with A[i].Consider the following element that is to be sorted using selection sort : 89, 45, 68, 90, 29, 34, 17.
The analysis of selection sort is straightforward. The input's size is given by the number of elements 'n' and the algorithm's basic operation is the key comparison A[j] < A[min]. The number of times it is executed depends only on the array's size.
![]() |
Selection Sort In C : Showing how elements are sorted |
The above figure shows how given elements 89, 45, 68, 90, 29, 34, 17 are sorted according to selection sort. Each line corresponds to one iteration of the algorithm i.e. a pass through the list tail to the right of the vertical bar. An element in bold indicates the smallest element found. Elements to the left of the vertical bar are in their final positions and are not considered in this and subsequent iterations.
SELECTION SORT ALGORITHM
SelectionSort(int a[],int n)
for i=0 to n-2
min=i
for j=i+1 to n-1
if a[min] > a[j]
min = j
swap a[i] with a[min]
SELECTION SORT PROGRAM IN C
// Selection sort program in c
#include<stdio.h>
void SelectionSort(int [],int);
int main()
{
int a[20],i,n;
printf("Enter number of elements in array : ");
scanf("%d",&n);
// Inputting elements
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
}
// Displaying Elements before selection sort
printf("Items in the array are : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
//Applying selection sort
SelectionSort(a,n);
// Displaying elements after selection sort
printf("\nElements after selection sort : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
return 0;
}
void SelectionSort(int a[],int n)
{
int i,loc,j,min,temp;
for(i=0;i<=n-2;i++)
{
min = i;
for(j=i+1;j<=n-1;j++)
{
// Finding minimum element
if(a[min] >a[j])
{
min=j;
}
}
//Swapping a[i] with a[min]
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
More Informative Posts :
- Insertion Sort Program In C
- Merge Sort Program In C
- Quick Sort Program In C
- Counting Sort Program In C
- Bubble Sort Program In C
- Heap Sort Program In C
- Bucket Sort Program In C
- Shell Sort Program In C
- Radix Sort Program In C