问题描述:
归并排序分治思想(divide and conquer)在排序中的具体应用,它的时间复杂度为O(NlgN)。问题和实现的详细描述
大家可参考维基百科;
代码实现:
#ifndef _MERGE_SORT_H_
#define _MERGE_SORT_H_
#include <assert.h>
#include <iostream>
#include <algorithm>
#include <functional>
#define MAXLEN 65535
/*
* implement merge for result sorted
*
*/
template<class T>
void Merge( T item[], int left, int mid, int right )
{
static T auxItem[MAXLEN];
int i;
for( i = mid + 1; i > left; i-- )
{
auxItem[i - 1] = item[i - 1];
}
int j;
for( j = mid; j < right; j++ )
{
auxItem[right + mid - j] = item[j + 1];
}
for( int k = left; k <= right; k++ )
{
if( auxItem[i] < auxItem[j] )
{
item[k] = auxItem[i++];
}
else
{
item[k] = auxItem[j--];
}
}
}
/*
* the implementation of merge sort
*
*/
template<class T>
void MergeSort( T item[], int left, int right )
{
if( left >= right )
return;
int mid = left + ((right - left) >> 1);
MergeSort( item, left, mid );
MergeSort( item, mid + 1, right );
Merge( item, left, mid, right );
}
/*
* Implement merge for sequence sorted
*
*/
template<class T>
void MergeAB( T c[], T a[], int n, T b[], int m )
{
for( int i = 0, j = 0, k = 0, k < m + n; k++ )
{
if( n == i )
{
c[k] = b[j++];
continue;
}
if( m == j )
{
c[k] = a[i++];
continue;
}
c[k] = (a[i] < b[j]) ? a[i++] : b[j++];
}
}
/*
* the implementation of merge sort
*
*/
template<class T>
void MergeSortBU( T item[], int left, int right )
{
for( int m = 1; m <= right - left; m = m + m )
{
for( int i = left; i <= right - m; i += m + m )
{
Merge( item, i, i + m - 1, min( i + m + m - 1, right) );
}
}
}
/*
* Test interface
*
*/
void TestMergeSort()
{
int arr[] = {11, 2, 4, 32, 43, 44, 74, 21, 111, 1111, 999, 77, 33, 22, 11111, 66, 88, 38, 386};
int len = sizeof(arr)/sizeof(arr[0]);
MergeSort( arr, 0, len - 1 );
for( int i = 0; i < len; i++ )
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
//test another implementation
int length = 100;
int* item = new int[length];
assert( item );
for( int i = 0; i < length; i++ )
{
item[i] = i;
}
std::random_shuffle( item, item + length );
MergeSortBU( item, 0, length - 1 );
for( int i = 0; i < length; i++ )
{
if( !(i % 10) && i )
{
std::cout << std::endl;
}
std::cout << item[i] << " ";
}
delete [] item;
}
#endif