In this tutorial, we will describe the Insertion Sort program in c programming language. Insertion Sort works in the way we sort the playing cards in our hands. The Insertion Sort algorithm is used to re-arrange the elements of an array in ascending order.
Copy the below c program and execute it with the help of c compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #include <stdio.h> #include <math.h> void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i-1; 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[] = {20, 31, 43, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0; } |
5 6 20 31 43
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: Algorithm, array, Asymptotic Analysis, basic to advanced concepts with examples including Overview, Binary, Circular List, Data Structures, Data Structures and Algorithms Insertion Sort, Divide and Conquer, Doubly Linked List, Dynamic Programming, Environment Setup, Greedy Algorithms, Interpolation Search, Learn Data Structures and Algorithm using c, Linear, Linked List, Parsing Expression, Priority queue, Queue, Sorting Algorithm, Sorting techniques, Stack