Description: Insertion sort is a simple and intuitive sorting algorithm that builds a sorted list one element at a time. It works by taking an element from the unsorted portion and inserting it into the correct position in the sorted portion of the list.
Here's a C++ implementation of insertion sort:
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i]; // Element to be inserted
int j = i - 1;
// Shift elements of arr[0..i-1] that are greater than key
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
// Place key at its correct position
arr[j + 1] = key;
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
insertionSort function takes an array and its size as parameters.key, which will be inserted into the sorted portion of the array.while loop shifts elements in the sorted portion that are greater than key to the right, creating a space for key.key is inserted into the array.Insertion sort is efficient for small data sets or nearly sorted arrays. While it has a quadratic time complexity in the worst case, its best-case performance and stability make it useful in practice for certain scenarios. Insertion sort is often used in conjunction with other algorithms, like in hybrid sorting algorithms, where it efficiently sorts small subarrays.
Open this section to load past papers