Selection Sort in C Programming

In this source code example, we will write a code to implement the Selection Sort algorithm in the C programming language.

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning.

Selection Sort in C Programming

In this C program, we will take input from the User or console. Let's write a C program to sort N numbers in ascending order using the Selection Sort algorithm:

#include<stdio.h>

void Selectionsort(int[], int);

void main() {
	int x[20], i, n;
	printf("\n Enter the no of element to be sorted:");
	scanf("%d", &n);
	printf("\n Enter %d elements:", n);
	for (i = 0; i < n; i++)
		scanf("%d", &x[i]);
	Selectionsort(x, n);
	printf("\n The sorted array is:\n");
	for (i = 0; i < n; i++)
		printf("%4d", x[i]);
}

void Selectionsort(int a[], int n) {
	int i, j, pos, large;
	for (i = n - 1; i > 0; i--) {
		large = a[0];
		pos = 0;
		for (j = 1; j <= i; j++) {
			if (a[i] > large) {
				large = a[j];
				pos = j;
			}
		}
		a[pos] = a[i];
		a[i] = large;
	}
}

Output:


 Enter the no of element to be sorted:
5

 Enter 5 elements:
50
30
10
20
40

 The sorted array is:
  10  30  20  40  50

Related Algorithms in C Programming


Comments