Insertion Sort Program in C Using Array

Insertion sort program in c using array. Using this program we can execute a sorting program in c using an array for beginners.

Insertion Sort in C

In C, insertion sort is a basic sorting algorithm that divides an array into sorted and unsorted parts, then selects and places the values from the unsorted portions in the correct positions in the sorted part. 

Insertion sort is a simple sorting algorithm in which each item in the final sorted array (or list) is added one at a time. On huge lists, it is substantially less efficient than more complex algorithms like quicksort, heapsort, or merge sort.

Array Definition in C

An array is a collection of data elements of the same type stored in contiguous memory regions. Arrays are a derived data type in the C programming language that may hold primitive data types like int, char, double, float, and so on. 

An array is a collection of elements of the same kind that are stored in contiguous memory locations and may be accessed separately using a unique identifier’s index.

Insertion Sort Program in C Using Array

#include<stdio.h>
int main()
{
int n, i, j, temp;
int arr[64];
printf("Enter Number of Elements\n");
scanf("%d", &n);
printf("Enter %d Integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1 ; i <= n - 1; i++)
{
j = i;
while ( j > 0 && arr[j-1] > arr[j])
{ 
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j--;
}
}
printf("Sorted List In Ascending Order\n");
for (i = 0; i <= n - 1; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}

Output:

Enter Number of Elements
3
Enter 3 Integers
34
56
78
Sorted List In Ascending Order
34
56
78