TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
Binary Insertion Sort Algorithm (Insertion Sort) 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<class T > | |
int64_t | sorting::binary_search (std::vector< T > &arr, T val, int64_t low, int64_t high) |
Binary search function to find the most suitable pace for an element. | |
template<typename T > | |
void | sorting::insertionSort_binsrch (std::vector< T > &arr) |
Insertion sort function to sort the vector. | |
static void | test () |
Self-test implementations. | |
int | main () |
Main function. | |
Binary Insertion Sort Algorithm (Insertion Sort)
If the cost of comparisons exceeds the cost of swaps, as is the case for example with string keys stored by reference or with human interaction (such as choosing one of a pair displayed side-by-side), then using binary insertion sort may yield better performance. Binary insertion sort employs a binary search to determine the correct location to insert new elements, and therefore performs ⌈log2 n⌉ comparisons in the worst case. When each element in the array is searched for and inserted this is O(n log n). The algorithm as a whole still has a running time of O(n2) on average because of the series
Example execution steps:
\begin{bmatrix}40 &30 &20 &50 &10\end{bmatrix}
\begin{bmatrix}30 &40 &20 &50 &10\end{bmatrix}
\begin{bmatrix}20 &30 &40 &50 &10\end{bmatrix}
\begin{bmatrix}10 &20 &30 &40 &50\end{bmatrix}
Definition in file binary_insertion_sort.cpp.
int main | ( | void | ) |
Main function.
Definition at line 143 of file binary_insertion_sort.cpp.
|
static |
Self-test implementations.
Definition at line 104 of file binary_insertion_sort.cpp.