Thursday, April 9, 2026

Write a program that sorts the given array of integers using insertion sort in ascending order || C Lab Program

 WAP_F05: Write a C program that sorts the given array of integers using insertion sort in ascending order || Sorting and Searching


WAP_F05: C Lab Program


//The given array of integers using insertion sort in ascending order.
#include <stdio.h>

int main() {
    int arr[50], n, i;
    void insertionSort(int [], int );

    // Input number of elements
    printf("Enter number of elements: ");
    scanf("%d", &n);

    // Input array elements
    printf("Enter %d integers:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Call insertion sort function
    insertionSort(arr, n);

    // Print sorted array
    printf("Array sorted in ascending order:\n");
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

// Function to perform insertion sort in ascending order
void insertionSort(int arr[], int n) {
    int i, key, j;

    for (i = 1; i < n; i++) {
        key = arr[i];      // Element to insert
        j = i - 1;

        // Shift elements that are greater than key
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }

        // Insert key at correct location
        arr[j + 1] = key;
    }
}



OUTPUT


Enter number of elements: 9
Enter 9 integers:
4 5 6 1 7 2 8 3 9
Array sorted in ascending order:
1 2 3 4 5 6 7 8 9


For all 2026 published articles list: click here

...till the next post, bye-bye & take care