Insertion Sort in C Programming


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

Insertion sort is an algorithm that creates a final sorted array one element at a time. The algorithm's performance is of the order O(n2). This algorithm is less efficient on large collections than other algorithms, such as quick, heap, and merge sort.

In real life, a good example of insertion sort is the way cards are manually sorted by the players in a game of bridge.

Insertion 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 Insertion Sort algorithm:

#include<stdio.h>

void Insertionsort(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]);
	Insertionsort(x, n);
	printf("\n The sorted array is:\n");
	for (i = 0; i < n; i++)
		printf("%4d", x[i]);
}

void Insertionsort(int a[], int n) {
	int i, j, key;
	for (j = 1; j < n; j++) {
		key = a[j];
		i = j - 1;
		while ((i > -1) && (a[i] > key)) {
			a[i + 1] = a[i];
			i = i - 1;
		}
		a[i + 1] = key;
	}
}

Output:


 Enter the no of element to be sorted: 7

 Enter 7 elements:
70
50
60
30
40
20
10

 The sorted array is:
  10  20  30  40  50  60  70

Related Algorithms in C Programming


Comments