C Program to Implement Selection Sort

The selection sort works by finding the smallest value from the array and placing it in the smallest index(in ascending) in every iteration. This step is done until all the elements of an array is sorted.

Also Read: C Program to Implement BubbleSort with Function

Pseudo Code of Selection Sort:

Let A be the array and it has n elements then the pseudocode of selection sort is follows:

SelectionSort(A,n)
{
	for(i=0;i<n-1;i++)
	{
		least=A[i];
		loc=i;
		for(j=i+1;j<n;j++)
		{
			if(least>A[j])
			{
				least=A[j];
				loc=j;
			}
		}
		swap(A[i],A[loc]);	
	}
	
}

Code in C:

#include<stdio.h>
#include<conio.h>

void SelectionSort(int[],int);

int main()
{
	int i;
	int n;
	int a[20];
	printf("How many numbers you want to sort: ");
	scanf("%d",&n);
	
	printf("\nEnter %d numbers: ",n);
	for(i=0;i<n;i++)
	{
		printf("\nEnter %dth number: ",i+1);
		scanf("%d",&a[i]);
	}
	SelectionSort(a,n);
	getch();
	return(0);
}


void SelectionSort(int a[],int n)
{
	int i;
	int j;
	int least;
	int loc;
	int temp;
	
	for(i=0;i<n-1;i++)
	{
		least=a[i];
		loc=i;
		for(j=i+1;j<n;j++)
		{
			if(least>a[j])
			{
				least=a[j];
				loc=j;
			}
		}
		
		temp=a[i];
		a[i]=a[loc];
		a[loc]=temp;
		
	}
	
	printf("\nThe sorted array is: ");
	for(i=0;i<n;i++)
	{
		printf("%d\t",a[i]);
	}
}

Output:

C Program to Implement Selection Sort 1

Do comment down if you have any queries.

Also Read: Function In C Programming

LEAVE A REPLY

Please enter your comment!
Please enter your name here