Insertion Sort is a simple sorting technique that builds the final sorted array one item at a time. It is much like sorting playing cards in your hands.
Given Array: [5, 2, 4, 6]
#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 a[] = {5, 2, 4, 6}; int n = 4; insertionSort(a, n); for (int i = 0; i < n; i++) { printf("%d ", a[i]); } return 0; }
ā±ļø Time Complexity:
Worst Case: O(n²)
Best Case: O(n) (when array is already sorted)
Average Case: O(n²)
š Space: O(1) (In-place sorting)
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!