TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
Insertion Sort Algorithm. More...
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
Go to the source code of this file.
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:
Definition in file insertion_sort_recursive.cpp.
|
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 |
Definition at line 94 of file insertion_sort_recursive.cpp.
int main | ( | void | ) |
Main function.
run self test implementations
Definition at line 149 of file insertion_sort_recursive.cpp.
|
static |
self test implementation
Definition at line 105 of file insertion_sort_recursive.cpp.