Aim: Implement insertion sort in C
#include <stdio.h> int main() { int arr[5], length = 5, i, j, temp,n,key; printf("Enter the number of elements : "); scanf("%d",&n); printf("Enter %d numbers : ",n); for (i = 0; i < n; i++) { scanf("%d",&arr[i]); } for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; while (key < arr[j] && j >= 0) { arr[j + 1] = arr[j]; --j; } arr[j + 1] = key; } printf("Sorted array is : "); for (i = 0; i < n; i++) { printf(" %d ",arr[i]); } return 0; }
Output
Enter the number of elements : 5 Enter 5 numbers : 11 99 44 77 22 Sorted array is : 11 22 44 77 99