1. 归并排序算法?
其基本思想是:假设初始序列含有n个记录,则可以看成是n个有序的子序列,每个子序列的长度是1,然后两两归并,得到[n/2]个长度为2或1的有序子序列;再两两归并,…..,如此重复,直至得到一个长度是n的有序序列为止。
2. 时间复杂度
总体的复杂度为O(NlogN)
// MergeSort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <iterator>//back_inserter
#include <algorithm>//copy
using namespace std;
int gen_rand() { return rand() % 100; }
// -------------------------------------
// merges the left and right subvectors
// -------------------------------------
template <typename IterType>
vector<int> my_merge(IterType left_first, const IterType left_last,IterType right_first, const IterType right_last )
{
vector<int> result;
while ( (left_first < left_last) || (right_first < right_last) )
{
if ( (left_first < left_last) && (right_first < right_last) )
{
if ( *(left_first) <= *(right_first) )
{
result.push_back( *left_first );
++left_first;
}
else
{
result.push_back( *right_first );
++right_first;
}
}
else if ( left_first < left_last )
{
for ( ; left_first < left_last; ++left_first )
{
result.push_back( *left_first );
}
}
else if ( right_first < right_last )
{
for ( ; right_first < right_last; ++right_first )
{
result.push_back( *right_first );
}
}
}
return result;
}
// -------------------------------------
// merge sort
// -------------------------------------
template < typename IterType>
vector<int> merge_sort( IterType first, IterType last )
{
int middle = ( last - first )/2;
vector<int> left, right;
// size is one
if ( middle < 1 )
{
left.push_back( *first );
return left;
}
// recursion
left = merge_sort( first, first + middle );//左闭合区间
right = merge_sort( first + middle, last );
return ( my_merge( left.begin(), left.end(), right.begin(), right.end() ) );
}
int main(int argc, char* argv[])
{
int num_items = 20;
// Seed the RNG - Ramdon Number Generator
srand( time( NULL ) );
// ----------------------------------------
// creates a vector of random int values
// ----------------------------------------
vector<int> iVec;
iVec.reserve(num_items);
generate_n( std::back_inserter(iVec), num_items, gen_rand );
// call sort function
iVec = merge_sort( iVec.begin(), iVec.end() );
// print the vector
std::ostream_iterator<int> os( cout, "\t\t" );
copy( iVec.begin(), iVec.end(), os );
cout << endl;
return 0;
}
结果如下: