Sorting an Array Using Insertion Sort Algorithm in C++

This exercise focuses on implementing the insertion sort algorithm to sort an array of integers. Insertion sort works similarly to how we sort playing cards in our hands. The algorithm builds the final sorted array one element at a time by comparing each new element to those before it and inserting it in its proper place. Though it has a time complexity of O(n²) in the worst case, it is intuitive and performs well on small or nearly sorted datasets. You will write a function to perform insertion sort and then use it in the main function to sort a predefined array of integers. This activity will help you understand basic sorting techniques and how elements are shifted during sorting.

Group

Search and Sort Algorithms in C++

Objective

Create a function called insertionSort that accepts an array of integers and its size. Inside the function, implement the insertion sort algorithm by iterating through the array and inserting each element into its correct position in the sorted portion of the array. In the main function, define an unsorted array and use the insertionSort function to sort it. Finally, print the sorted array.

Create a program that sorts an array using the insertion sort algorithm.

Example C++ Exercise

 Copy C++ Code
#include <iostream>   // Include the input-output stream library
using namespace std;

// Function to perform insertion sort on an array
void insertionSort(int arr[], int size) {
    // Loop through elements starting from the second one
    for (int i = 1; i < size; i++) {
        int key = arr[i];      // Store the current element
        int j = i - 1;

        // Move elements greater than key to one position ahead
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];  // Shift element to the right
            j = j - 1;            // Move to the previous element
        }

        arr[j + 1] = key;       // Place the key in its correct position
    }
}

int main() {
    // Declare and initialize an unsorted array
    int numbers[] = {9, 5, 1, 4, 3};
    int size = sizeof(numbers) / sizeof(numbers[0]);   // Calculate array size

    // Call the insertionSort function
    insertionSort(numbers, size);

    // Display the sorted array
    cout << "Sorted array: ";
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }
    cout << endl;

    return 0;   // End of program
}

 Output

Sorted array: 1 3 4 5 9 

Share this C++ Exercise


More C++ Programming Exercises of Search and Sort Algorithms in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.