C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Insertion Sort Program

C Program: Insertion Sort Program

C

#include <stdio.h>

 

int main() {

    int arr[100], n, i, j, key;

 

    // Input number of elements

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    // Input array elements

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

    for(i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }

 

    // Insertion Sort algorithm

    for(i = 1; i < n; i++) {

        key = arr[i];     // Take the current element

        j = i - 1;

 

        // Move elements greater than key one position ahead

        while(j >= 0 && arr[j] > key) {

            arr[j + 1] = arr[j];

            j--;

        }

 

        // Place key at its correct position

        arr[j + 1] = key;

    }

 

    // Display sorted array

    printf("\nSorted array in ascending order:\n");

    for(i = 0; i < n; i++) {

        printf("%d ", arr[i]);

    }

 

    printf("\n");

    return 0;

}

Output

 
INPUT :
Enter number of elements: 6
Enter 6 elements:
9 5 1 4 3 2

OUTPUT 2 :
Sorted array in ascending order:
1 2 3 4 5 9

Explanation

  1. Insertion Sort builds the sorted list one element at a time.
  2. For each element (starting from index 1), the algorithm compares it with previous elements and inserts it in the correct position.
  3. The left portion of the array is always sorted after each iteration.

Algorithm Steps

  1. Start from the second element (i = 1).
  2. Store it in key.
  3. Compare key with previous elements (arr[j]).
  4. Shift elements greater than key to one position ahead.
  5. Insert key at its correct position.
  6. Repeat for all elements.