1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
void merge(int A[],int lower,int middle,int higher);
void mergeSort(int A[],int lower,int higher);
int main()
{
srand(time(0));
int list[10];
for(int i=0;i<10;i++)
list[i]=rand()%100+1;
for(int i=0;i<10;i++)
cout<<list[i]<<" ";
cout<<endl<<endl;
mergeSort(list,0,9);
for(int i=0;i<10;i++)
cout<<list[i]<<" ";
cout<<endl;
system("PAUSE");
}
void merge(int A[],int lower,int middle,int higher)
{
int n1=(middle-lower)+1;
int n2=higher-middle;
vector<int> L(n1+1);
vector<int> R(n2+1);
for(int i=1;i<n1;i++)
{
L[i]=A[(lower+i)-1];
}
for(int j=1;j<n2;j++)
{
R[j]=A[middle+j];
}
L[n1+1]=0;
R[n2+1]=0;
int i=1,j=1;
for(int k=lower;k<higher;k++)
{
if(L[i]<=R[j])
{
A[k]=L[i];
i++;
}
else
{
A[k]=R[j];
j++;
}
}
}
void mergeSort(int A[],int lower, int higher)
{
int middle;
if(lower<higher)
{
middle=((lower+higher)/2);
mergeSort(A,lower,middle);
mergeSort(A,middle+1,higher);
merge(A,lower,middle,higher);
}
}
|