假设有两个人,每人手里都有一部分牌,而且每个人手中的牌都按大小顺序排列好了。
那么,现在要把两个人手中的牌合并到一起,并且合并后要从小到大依次排好,可以这样做:
每个人都从手中拿出最小的牌,然后比较,谁的牌小就把该张牌放在桌面上,牌大的一方牌仍然拿在手中,待下次再比较。
下一次每个人又拿最小的牌进行比较,如此下去。。。直到一方手中的牌全部放在了桌面上,这时另一方就可以把牌按从小到大的顺序全部放在桌面上了。
这时,桌面上的牌显然是排好了序的。
这就是归并排序法的主要思想。当然,有归并,首先就得分割,得把手中的牌分到两个人手中,然后分到四个人手中。。。
一直分到每人手中只有一张牌。然后才可以每两个人进行合并,最后合并到一个人的手中。
c++实现:
Sort.h文件
/*********************************************************************/
const int MAX=1000000000;
class Sort
{
const int arraySize;
float *array;
public:
Sort(int arraySize);
~Sort();
void Initial();
void Partition(int first, int last);// only called by function Merge()
void Merge(int first,int pivot, int last);//only called by function MergeSort()
void MergeSort();
void Show();
};
/*********************************************************************/
Sort.cpp文件
/*********************************************************************
#include <iostream>
#include "Sort.h"
#include <cmath>
using namespace std;
Sort::Sort(int size):arraySize(size)
{
}
void Sort::Initial()
{
array= new float[arraySize];
cout<<"please enter "<<arraySize<<" elements!"<<endl;
for(int i=0;i<arraySize;i++)
{
cin>>array[i];
}
cout<<"entered!"<<endl;
}
void Sort::Partition(int first, int last)
{
if(first<last)
{
int pivot=floor((last+first)/2);
Partition(first,pivot);
Partition(pivot+1,last);
Merge(first,pivot,last);
}
}
void Sort::Merge(int first, int pivot,int last)
{
int p=pivot-first+2;
int q=last-pivot+1;
float* L=new float[p];
float* R=new float[q];
for(int i=0;i<p-1;i++)
{
L[i]=array[first+i];
}
L[i]=MAX;
for(int j=0;j<q-1;j++)
{
R[j]=array[pivot+j+1];
}
R[j]=MAX;
i=0;
j=0;
for(int k=first;k<=last;k++)
{
if(L[i]<R[j])
{
array[k]=L[i++];
}
else
{
array[k]=R[j++];
}
}
delete[] L;
delete[] R;
}
void Sort::MergeSort()
{
Partition(0,arraySize-1);
}
void Sort::Show()
{
for(int i=0;i<arraySize;i++)
{
cout<<array[i]<<" ";
}
}
Sort::~Sort()
{
delete [] array;
}
/***********************************************************************/
main程序文件
/*********************************************************************/
#include <iostream>
#include "Sort.h"
using namespace std;
int main()
{
cout<<"enter the size of array!"<<endl;
int size;
cin>>size;
Sort test(size);
test.Initial();
test.MergeSort();
test.Show();
return 0;
}
/****************************************************************/
归并排序法(MergeSort)c++实现
最新推荐文章于 2022-07-17 12:40:05 发布