Skip to content
Home » C Programs » Insertion Sort in C Using Function

Insertion Sort in C Using Function

Basic insertion sort in c using function. In this program we can execute the insertion sort program for beginners to understand and how to sort the elements in c programming language.

For Loop Definition in C

The for loop in the C programming language is used to repeatedly iterate statements or sections of a program. It’s frequently used to traverse data structures like arrays and linked lists. In computer science, a for-loop is a control flow statement that specifies iteration and allows code to be executed several times. For-loops are typically used when the number of iterations is known before starting the loop. Using this looping statement we can execute the insertion sort in c using function.

Function Definition in C

A function is a collection of statements that work together to complete a task. Every C program contains at least one function, main(), and even the simplest programs can specify more functions. The name, return type, and parameters of a function are all specified in a function declaration.

Insertion Sort in C Using Function

//insertion sort in c using function 
#include<stdio.h>
#include<conio.h>
void insertion(int [], int );
int main()
{
int arr[30];
int i,size;
printf("\nInsertion Sort\n\n");
printf("Enter total no. of elements");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element",i+1);
scanf("%d",&arr[i]);
}
insertion(arr,size);
printf("\nAfter Sorting\n\n");
for(i=0; i<size; i++)
printf(" %d",arr[i]);
getch();
return 0;
}
void insertion(int arr[], int size)
{
int i,j,tmp;
for(i=0; i<size; i++)
{
for(j=i-1; j>=0; j--) 
{
if(arr[j]>arr[j+1])
{
tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
else
break;
}
}
}

Insertion Sort

Enter total no. of elements3
Enter 1 element45
Enter 2 element23
Enter 3 element45

After Sorting

23 45 45