📊📚Intermediate
Sort Array Using Insertion Sort
Sort using insertion sort
Insertion Sort builds the sorted array one element at a time by inserting each element into its correct position.
Program Code
insertion_sort.c
C
1#include <stdio.h>23int main() {4 int n;5 6 printf("Enter number of elements: ");7 scanf("%d", &n);8 9 int arr[n];10 printf("Enter %d elements: ", n);11 for (int i = 0; i < n; i++) {12 scanf("%d", &arr[i]);13 }14 15 // Insertion Sort16 for (int i = 1; i < n; i++) {17 int key = arr[i];18 int j = i - 1;19 20 // Move elements greater than key21 while (j >= 0 && arr[j] > key) {22 arr[j + 1] = arr[j];23 j--;24 }25 arr[j + 1] = key;26 }27 28 printf("Sorted array: ");29 for (int i = 0; i < n; i++) {30 printf("%d ", arr[i]);31 }32 printf("\n");33 34 return 0;35}Output
Enter number of elements: 5
Enter 5 elements: 12 11 13 5 6
Sorted array: 5 6 11 12 13
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials