数据结构之(归并排序)

来源:互联网 发布:淘宝上的催情药实测 编辑:程序博客网 时间:2024/06/01 12:45

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>//copyusing namespace std;intgen_rand(){ returnrand() % 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 );}}}returnresult;}// -------------------------------------//             merge sort// -------------------------------------template < typenameIterType>vector<int>merge_sort( IterType  first, IterType  last ){int middle = ( last - first )/2;vector<int>left, right;// size is oneif ( middle < 1 ){left.push_back( *first );returnleft;}// recursionleft  = merge_sort( first, first + middle );//左闭合区间right = merge_sort( first + middle, last );return( my_merge( left.begin(), left.end(), right.begin(), right.end() ) );}intmain(int argc, char* argv[]){intnum_items = 20; // Seed the RNG - Ramdon Number Generatorsrand( 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 functioniVec = merge_sort( iVec.begin(), iVec.end() );// print the vectorstd::ostream_iterator<int>os( cout, "\t\t" );copy( iVec.begin(), iVec.end(), os );cout << endl;return0;}

结果如下:


原创粉丝点击