Created
August 8, 2011 07:48
-
-
Save kazh98/1131365 to your computer and use it in GitHub Desktop.
Insertion Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Insertion Sort [License: CC-BY-SA] | |
* - Copyright(C) 2011 Kazh. All Rights Reserved. | |
*/ | |
#ifndef __INC_INSERTIONSORTH | |
#define __INC_INSERTIONSORTH | |
#include <iterator> | |
#include <algorithm> | |
/** Sorts the array by Insertion Sort Algorithm | |
* @tparam iter Random Access Iterator to access the array to sort | |
* @param[in,out] begin Pointer to head of the array to sort | |
* @param[in,out] end Pointer to tail of the array to sort | |
*/ | |
template < | |
typename iter | |
> | |
void insertionSort ( | |
iter begin, | |
iter end | |
) | |
{ | |
iter sorted = begin; | |
while ( std::distance ( ++begin, end ) > 0 ) | |
{ | |
iter p, q; | |
/* Binary Search */ | |
for ( p = sorted, q = begin; | |
std::distance ( p, q ) > 0; ) | |
{ | |
iter m = p + std::distance ( p, q ) / 2; | |
if ( *begin < *m ) | |
{ | |
q = m; | |
} | |
else /* if ( *begin >= *m ) */ | |
{ | |
p = m + 1; | |
} | |
} | |
/* Insert */ | |
for ( p = begin; p > q; --p ) | |
{ | |
std::iter_swap ( p, p - 1 ); | |
} | |
} | |
return ; | |
} | |
#endif /* __INC_INSERTIONSORTH */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment