top of page
Writer's picturePrateek Chauhan

Insertion Sort

It is an simple sorting algorithm that builds the final sorted array(or array) one at a time. Here, a sub-lists is maintained which is always sorted.

It is much less efficient on large lists than more advanced algorithms such as quick sort, heap sort or merge sort.

 

Example:

9, 8, 10, 5, 6

Let us loop for i = 1 (second element of the array) to 4 (last element of the array)

i = 1. Since 8 is smaller than 9, move 9 and insert 8 before 9 8, 9, 10, 5, 6

i = 2. 10 will remain at its position as all elements in A[0..I-1] are smaller than 10 8, 9, 10, 5, 6

i = 3. 5 will move to the beginning and all other elements from 8 to 10 will move one position ahead of their current position. 5, 8, 9, 10, 6

i = 4. 6 will move to position after 5, and elements from 8 to 10 will move one position ahead of their current position. 5, 6, 8, 9, 10

 

Another Example:

Here is an visual example of insertion sort.

 

Implementation in C:

// C program for insertion sort 
#include <math.h> 
#include <stdio.h> 
  
// Function to sort an array using insertion sort
void insertionSort(int arr[], int n) 
{ 
	int i, key, j; 
	for (i = 1; i < n; i++) { 
 		key = arr[i]; 
  		j = i - 1; 
  
 /* Move elements of arr[0..i-1], that are 
 greater than key, to one position ahead 
 of their current position */
 	while (j >= 0 && arr[j] > key) { 
  		arr[j + 1] = arr[j]; 
  		j = j - 1; 
 	} 
 	arr[j + 1] = key; 
 	} 
} 
  
// A utility function to print an array of size n 
void printArray(int arr[], int n) 
{ 
 	int i; 
 	for (i = 0; i < n; i++) 
		printf("%d ", arr[i]); 
	printf("\n"); 
} 
  
/* Driver program to test insertion sort */
int main() 
{ 
	int arr[] = { 9, 8, 10, 5, 6 }; 
 	int n = sizeof(arr) / sizeof(arr[0]); 
  
 	insertionSort(arr, n); 
 	printArray(arr, n); 
  
 return 0; 
} 
Output: 5 6 8 9 10
 

Miscellaneous:

Time Complexity: O(n*2). Learn more about time complexity here.

In-place: Yes

Stable: Yes



14 views0 comments

Recent Posts

See All

Heap Sort

Radix Sort

Comments


bottom of page