Insertion Sort in C: Algorithm, Code, and Step-by-Step Guide
By Rahul Singh
Updated on Jun 02, 2026 | 10 min read | 3.74K+ views
Share:
Looks like you're browsing from the
United StatesSome programs may not be available in your location
Some programs may not be available in your location
Switch to upGrad USAll courses
Certifications
More
By Rahul Singh
Updated on Jun 02, 2026 | 10 min read | 3.74K+ views
Share:
Table of Contents
Insertion sort in C is one of the simplest sorting algorithms you will learn as a programmer. It works the way you naturally sort playing cards in your hand: pick one card, find its right position among the already-sorted cards, and slide it in. Simple, intuitive, and a great starting point for understanding how sorting works under the hood.
In this blog, you will learn what insertion sort is, how the algorithm works, how to write the insertion sort program in C with a full working code, trace through a dry run, understand its time and space complexity, and see where it actually makes sense to use it. Whether you are just starting out or brushing up for interviews, this blog covers everything.
Ready to go beyond algorithms and start building real-world AI solutions? Explore upGrad’s Artificial Intelligence Courses to learn machine learning, generative AI, and cutting-edge technologies through hands-on projects and practical applications.
Insertion sort is a comparison-based sorting algorithm. It builds a sorted array one element at a time by picking each element and inserting it into its correct position in the already-sorted portion.
Think of it this way: you have a list of numbers. You start with the first element (it is already "sorted" on its own). Then you take the second element and compare it with the first. If it is smaller, you move it before the first. You continue doing this for each element until the entire array is sorted.
The insertion sort algorithm in C is especially useful when you are working with small datasets or nearly sorted data. For large, random datasets, faster algorithms like merge sort or quicksort are better choices.
Also Read: Data Structures and Algorithms (DSA)
Before writing any code, understand the logic step by step.
The algorithm:
Let us sort this array: {5, 3, 8, 1, 4}
Sorted array: {1, 3, 4, 5, 8}
Each pass grows the sorted portion by one element. By the last pass, the entire array is sorted.
Also Read: Insertion Sort Algorithm in Data Structures
Here is the complete insertion sort code in C. It is clean, well-commented, and beginner-friendly.
#include <stdio.h>
// Function to perform insertion sort
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i]; // Element to be placed correctly
j = i - 1;
// Shift elements greater than key one position to the right
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
// Place key in its correct position
arr[j + 1] = key;
}
}
// Function to print array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Main function
int main() {
int arr[] = {5, 3, 8, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
insertionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Output:
Original array: 5 3 8 1 4
Sorted array: 1 3 4 5 8
The outer for loop runs n-1 times. The inner while loop runs a variable number of times depending on how many elements need shifting.
Also Read: Understanding While Loop in Python with Examples
If you want to sort a user-defined array, here is the modified insertion sort program in C:
#include <stdio.h>
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
insertionSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
This version reads input at runtime, making it flexible for any dataset.
Also Read: Insertion Sort in Java: Explained with Examples
Understanding complexity is essential for interviews and for choosing the right algorithm in real-world situations.
Case |
Condition |
Complexity |
| Best Case | Array is already sorted | O(n) |
| Average Case | Elements are in random order | O(n²) |
| Worst Case | Array is sorted in reverse order | O(n²) |
Why O(n) in the best case? When the array is already sorted, the inner while loop never executes. The outer loop runs n-1 times, so total comparisons are just n-1. That is linear time.
Why O(n²) in the worst case? When the array is reverse sorted, every element needs to be shifted past all previously sorted elements. For n elements, total shifts are 1 + 2 + 3 + ... + (n-1) = n(n-1)/2, which is O(n²).
Insertion sort in C uses O(1) auxiliary space. It works directly on the input array. No extra array is created. Only a single key variable is needed.
Algorithm |
Best |
Average |
Worst |
Space |
Stable |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
Insertion sort outperforms even merge sort for very small arrays (fewer than 10-15 elements) due to low overhead. Many standard library sort implementations switch to insertion sort for small subarrays for this exact reason.
Choosing the right algorithm matters. Here is when insertion sort is a good pick:
Also Read: Time and Space Complexity in Machine Learning Algorithms Explained
Once you understand the basic version, you can explore these variations:
Instead of using loops, you can write insertion sort recursively.
void recursiveInsertionSort(int arr[], int n) {
if (n <= 1)
return;
// Sort first n-1 elements
recursiveInsertionSort(arr, n - 1);
// Insert last element at its correct position
int last = arr[n - 1];
int j = n - 2;
while (j >= 0 && arr[j] > last) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = last;
}
The logic is the same. The difference is that each recursive call sorts a smaller portion, and then the last element is inserted.
Instead of using linear search to find the correct position, you use binary search. This reduces the number of comparisons from O(n²) to O(n log n), but the number of shifts is still O(n²). So the overall time complexity remains O(n²) for shifts, but comparisons improve.
int binarySearch(int arr[], int item, int low, int high) {
while (low <= high) {
int mid = (low + high) / 2;
if (item == arr[mid])
return mid + 1;
else if (item > arr[mid])
low = mid + 1;
else
high = mid - 1;
}
return low;
}
void binaryInsertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int pos = binarySearch(arr, key, 0, i - 1);
int j = i - 1;
while (j >= pos) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
Binary insertion sort is useful when comparisons are expensive (for example, comparing strings or complex objects).
Insertion sort in C is a clean, simple algorithm that every programmer should know. It is not the fastest for large datasets, but it shines when dealing with small arrays or nearly sorted data. The insertion sort code in C is easy to write, easy to debug, and easy to explain, which makes it a go-to choice for learning the fundamentals of sorting.
If you want to go deeper into data structures and algorithms, exploring more complex algorithms like merge sort, quicksort, and heap sort will build a strong foundation for coding interviews and real-world software development.
Want personalized guidance on AI and upskilling? Speak with an expert for a free 1:1 counselling session today.
Insertion sort in C is a simple comparison-based sorting algorithm that builds a sorted array one element at a time. It picks each element from the unsorted portion and places it in its correct position within the already-sorted portion. It is efficient for small or nearly sorted datasets.
The best-case time complexity of insertion sort is O(n), which occurs when the array is already sorted. The average and worst-case complexities are both O(n²). The worst case happens when the array is sorted in reverse order, requiring maximum comparisons and shifts.
Yes, insertion sort is a stable sorting algorithm. When two elements have equal values, insertion sort preserves their original relative order. This makes it suitable for use cases where stability matters, such as sorting records by multiple fields.
The space complexity of insertion sort in C is O(1). It is an in-place sorting algorithm that sorts the array without needing any additional arrays or data structures. Only a constant amount of extra memory is used for the key variable and loop counters.
Both insertion sort and bubble sort have O(n²) average and worst-case time complexity. However, insertion sort generally performs fewer comparisons than bubble sort. Insertion sort shifts elements to place each item in position, while bubble sort repeatedly swaps adjacent elements. Insertion sort is usually preferred between the two.
Yes, insertion sort handles duplicate elements correctly. Since it is a stable algorithm, duplicate elements retain their original order after sorting. The algorithm compares values and only shifts elements that are strictly greater than the key, so equal elements are not displaced.
Binary insertion sort in C is a variation of insertion sort that uses binary search to find the correct position of each element instead of linear search. This reduces the number of comparisons to O(n log n), but the number of shifts remains O(n²), so the overall time complexity does not change.
You should use insertion sort in C when the array is small (typically fewer than 20-30 elements) or nearly sorted. Quicksort has better average performance at O(n log n), but its overhead makes it slower for tiny arrays. Many hybrid algorithms like Timsort use insertion sort for small subarrays for this reason.
When the input array is already sorted, the inner while loop in the insertion sort code in C never executes because no element needs to be shifted. The outer loop runs n-1 times with only one comparison each, making the time complexity O(n). This is the best-case scenario for insertion sort.
Recursive insertion sort in C follows the same logic as the iterative version but uses function calls instead of loops. It recursively sorts the first n-1 elements and then inserts the last element in the correct position. The space complexity increases to O(n) due to the recursion call stack.
Yes, insertion sort is used in real-world scenarios. It is part of hybrid sorting algorithms like Timsort (used in Python and Java) for handling small subarrays. It is also used in embedded systems with limited memory, online sorting where data arrives incrementally, and anywhere where simplicity and low overhead are more important than raw speed.
46 articles published
Rahul Singh is an Associate Content Writer at upGrad, with a strong interest in Data Science, Machine Learning, and Artificial Intelligence. He combines technical development skills with data-driven s...