## C Program For Insertion Sort Algorithm in Data Structure

Learn How To Sort Integer Arrays using Insertion Sort Algorithm in C Programming Language. It is important that we should know about **How A For Loop Works** before getting further with the C Program Code. The insertion sort technique is very simple to implement and is efficient when the number of elements to be sorted are less.

#### What is Insertion Sort Algorithm?

In this algorithm, every **Element** is **Inserted** at a **proper place** in a **Sorted List**. It is the same technique used while playing **Cards**. The Array is considered to be divided into two parts.

Initially, the Sorted part contains only the first element of the list and Unsorted part contains the remaining elements. In every pass, the first element from the Unsorted part is taken and inserted into the Sorted part at appropriate places. For n elements in the list, the list gets Sorted after n – 1 passes.

#### Insertion Sort Algorithm Analysis

Insertion Sort is a **Stable Sort**. Since it requires only one Temporary variable, it is an** In-Place Sort**. Space Complexity is O(1). The **best case** scenario would fetch run time complexity of **O(n)** when the data is already in sorted order. The **worst case** is when the data is in reverse order which will be having a run time complexity of **O(n ^{2})**.

#### C Program To Sort Arrays using Insertion Sort Algorithm

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 | #include<stdio.h> int main() { int arr[20], temp, i, j; int limit; printf("Enter Limit for Array:\t"); scanf("%d", &limit); printf("\nEnter %d Elements in the Array\n", limit); for(i = 0; i < limit; i++) { scanf("%d", &arr[i]); } for(i = 1; i < limit; i++) { temp = arr[i]; for(j = i - 1; j >= 0 && temp < arr[j]; j--) { arr[j + 1] = arr[j]; } arr[j + 1] = temp; } printf("\nSorted List:\n"); for(i = 0; i < limit; i++) { printf("%d\t", arr[i]); } printf("\n"); return 0; } |

#### Output

If you have any compilation errors or doubts in this Code To Sort Array using Insertion Sort C Program in Data Structures, let us know about in the Comment Section below.

Thanks.

You’re welcome Pankaj.

The simplicity of the program explanation is too good.

You’re welcome! We focus on making programs simpler to understand and this Insertion Sort in C Program is its example!