binary Insert Sort (Binary insertion sort) detailed and code (c + +)
This article address: http://blog.csdn.net/caroline_wendy/article/details/24001053
binary Insert Sort , where you find the insertion point, and you can use binary to find it.
This can reduce the number of comparisons, the number of moves is unchanged,
Time complexity is still O (n^2);
Code:
* * * test.cpp * * Created on:2014.04.18 *
author:spike/
/*eclipse CDT, gcc 4.8.1* /
#include <iostream>
#include <deque>
using namespace std;
void Binsertsort (std::d eque<int>& L) {for
(std::size_t i=2; i<l.size (); ++i) {
l[0] = l[i];
int low = 1, high = i-1;
Find L[0 's position while
(low <= high) {
int m = (low + high)/2;
if (L[0] < l[m]) high = m-1;
else low = m+1;
}
Move the larger forward for
(int j=i-1; j>=high+1;--j) l[j+1] = l[j];
L[HIGH+1] = l[0];
}
void print (const std::d eque<int>& L) {for
(std::size_t i=0 i < l.size (); ++i) {
std::cout << ; L[i] << "";
}
Std::cout << Std::endl;
}
int main () {
std::d eque<int> L = {0, 5, 2, 4, 3, 1};
Print (L);
Binsertsort (L);
Print (L);
return 0;
}
Output:
0 5 2 4 3 1 1 1 2 3 4-
5