C Program to Sort an array using Selection Sort in Ascending Order

Share

The program sorts uses Selection Sort technique to sort the given array. There are bunch of sorting mechanisms such as Bubble sort, Insertion sort and more to achieve this functionality. In this, we’ll be only focusing Selection Sort .

Selection Sort

Selection sort is a sorting technique wherein at each iteration, a minimum element is selected from an unsorted array and compared with all other remaining elements. if an element is found that is smaller than already assumed minimum element,  swapping would be performed.

It divides an array into two parts. One that is already sorted and another one which is still unsorted that need to be arranged.

From unsorted sublist, the algorithm finds the minimum element and adds on to sorted category. It ends when we get a single consolidated sorted sublist.

Pseudocode

FOR i=0 to Array.Length
minimum = i
FOR j=0 to Array.Length
if A[min]< A[j])
Swap A[min] with A[j]
End IF
END FOR
END FOR

C program to sort an array using Selection Sort in Ascending Order

#include<conio.h>
#include<stdio.h>
#define size 5
void main()
{
int arr[size],i,j,temp,min;
printf("Please enter elements: \n "); 
for(i=0;i<=size-1;i++)
{
scanf("%d",&arr[i]);
}

for(i=0;i<=size-1;i++)
{
min= i;
for(j=0;j<=size-1;j++)
{
if(arr[min]<arr[j]){
temp = arr[j];
arr[j] =arr[min];
arr[min] = temp;
}
}
}

printf(" \n Entered Elements :");

for(i=0;i<=size-1;i++)
{
printf("\n %d ",arr[i]);
} 
getch();

}

Output:

 

How does Selection Sort work?

 

Lastly, it is an inefficient algorithm for the large dataset as it requires O(n2) comparisons in all cases worst, average and best case. It is simple and occasionally has an upper hand over other complicated algorithms.

This post was last modified on March 10, 2024

Sandeep Verma

Published by
Sandeep Verma
Tags: array C c program daa design and algorithm analysis Pseudocode Selection sort sorting