Sorting algorithm : insertion sort in C

Insertion sort takes all the element one by one and place it to the right position for sorting that list. In this C programming guide, we will see some program belongs to insertion sort in C. See bellow to know the function of insertion sort.

Let’s try to understand how this sorting algorithm works.

insertion-sort-in-c-c-program-using-insertion-sort

C program using insertion sort in C

In this program we will take the elements from the user and then sort it using insertion sort algorithm. After sorting we will finally print the sorted list. Now, go to the program.

// program using insertion sort in C

#include<stdio.h>

int main(){
  int nums, c, d, t, number_arr[50];

  printf("Enter how many integers you want to sort : ");
  scanf("%d", &nums);

  printf("Enter %d elements here : \n", nums);

  for(c = 0; c < nums; c++){
    scanf("%d", &number_arr[c]);
  }

  for(c = 1; c < nums; c++){
    t = number_arr[c];
    d = c-1;

    while((t < number_arr[d]) && (d >= 0)){
      number_arr[d + 1] = number_arr[d];
      d = d - 1;
    }
    number_arr[d + 1] = t;
  }

  printf("\nSorted array is : \n");
  for(c = 0; c < nums; c++){
    printf("%d ", number_arr[c]);
  }
  return 0;
}

Output of insertion sort program:

Enter how many integers you want to sort : 6
Enter 6 elements here :
20 40 12 34 91 2

Sorted array is :
2 12 20 34 40 91

You can also implement insertion sort algorithm using function and recursion. If you get the clear idea about insertion sort then try yourself to make the same program using function in C.

Previous pageBubble sort

Next pageSelection sort