w3resource

C Exercises: Insertion sort algorithm

C Programming Searching and Sorting Algorithm: Exercise-3 with Solution

Write a C program to sort a list of elements using the insertion sort algorithm.

Note:
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than other algorithms such as quicksort, heapsort, or merge sort.

Visual presentation - Insertion search algorithm:

C programming Insertion sort algorithm

Sample Solution:

Sample C Code:

#include<stdio.h>

int main() {
    int arra[10], i, j, n, array_key;

    // Input the number of values in the array
    printf("Input no. of values in the array: \n");
    scanf("%d", &n);

    // Input array values
    printf("Input %d array value(s): \n", n);
    for (i = 0; i < n; i++)
        scanf("%d", &arra[i]);

    /* Insertion Sort */
    for (i = 1; i < n; i++) {
        array_key = arra[i];
        j = i - 1;

        // Move elements greater than array_key to one position ahead of their current position
        while (j >= 0 && arra[j] > array_key) {
            arra[j + 1] = arra[j];
            j = j - 1;
        }

        // Insert array_key at its correct position
        arra[j + 1] = array_key;
    }

    // Print the sorted array
    printf("Sorted Array: \n");
    for (i = 0; i < n; i++)
        printf("%d  \n", arra[i]);

    return 0;
}

Sample Input:

3
12
15
56

Sample Output:

Input  no. of values in the array: 
Input  3 array value(s): 
Sorted  Array: 
12  
15  
56  

Flowchart:

Flowchart: C Programming - Insertion sort

C Programming Code Editor:

Previous: Write a C program to sort a list of elements using the bubble sort algorithm.
Next: Write a C program to sort a list of elements using the merge sort algorithm.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/searching-and-sorting/c-search-and-sorting-exercise-4.php