|
Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
|
Insertion Sort Algorithm. More...
#include <algorithm>#include <cassert>#include <iostream>#include <vector>Namespaces | |
| namespace | sorting |
| for working with vectors | |
Functions | |
| template<typename T > | |
| void | sorting::insertionSort (T *arr, int n) |
| Insertion Sort Function. | |
| template<typename T > | |
| void | sorting::insertionSort (std::vector< T > *arr) |
| Insertion Sort for a vector. | |
| template<typename T > | |
| static void | create_random_array (T *arr, int N) |
| Helper function to create a random array. | |
| static void | tests () |
| self test implementation | |
| int | main () |
| Main function. | |
Insertion Sort Algorithm.
Insertion sort is a simple sorting algorithm that builds the final sorted array one element at a time. It is much less efficient compared to other sorting algorithms like heap sort, merge sort, or quick sort.
However, it has several advantages:
Insertion sort works similarly to how people sort playing cards in their hands. The algorithm iterates through the list and inserts each element into its correct position in the sorted portion of the array.
The time complexity of the algorithm is \(O(n^2)\), and in some cases, it can be \(O(n)\).
Example execution:
|
static |
Helper function to create a random array.
| T | Type of the array elements |
| arr | Array to fill (must be pre-allocated) |
| N | Number of elements in the array |
| int main | ( | void | ) |
|
static |
self test implementation