Insertion Sort Program in C - Insertion Sort



 insertion Sort using c program

Learn C - C tutorial - insertion Sort using c program - C examples - C programs

Insertion Sort

  • Insertion sort is a simple sorting algorithm.
  • Insertion sort is less efficient on large lists than more advanced algorithms.For Example,
 Insertion Sort program in c

Learn C - C tutorial - Insertion Sort program in C - C examples - C programs

Sample code

#include <stdio.h>
#include <stdlib.h>
void PrintArray(int *array, int n)
{
    for (int i = 0; i < n; ++i)
        printf("%d ", array[i]);
    printf("\n");
}
void InsertionSort(int arr[], int arr_size)
{
    if(arr_size > 1)
    {
        int size = arr_size;
        for(int i = 1; i < size; ++i)
        {
            int j = i - 1;
            int key = arr[i];
            while(j > = 0 && arr[j] > key)
            {
                arr[j+1] = arr[j];
                --j;
            }
            arr[j+1] = key;
        }
    }
}
int main()
{
    int array[] = {94, 42, 333, 65, 54, 1, 12};
    int n = sizeof(array)/sizeof(array[0]);
    printf("Before Insertion Sort :\n");
    PrintArray(array, n);
    InsertionSort(array, n);
    printf("After Insertion Sort :\n");
    PrintArray(array, n);
    return (0);
}

Output

Before Insertion Sort :
94 42 333 65 54 1 12 
After Insertion Sort :
1 12 42 54 65 94 333 



View More Quick Examples


Related Searches to Insertion Sort Program in C - Insertion Sort