合并两个已排好序的数组, Merge算法将会用于下一节的自底向上合并排序算法。
#include <stdio.h>
#include <iostream.h>
#include <stdlib.h>
#define Low 0
#define Middle 3
#define High 10
int main(void)
{
int A[High+1] = {2,11,45,57,3,6,13,24,25,65,68};
int B[High+1] = {0,0,0,0,0,0,0,0,0,0,0};
int low = 0;
int middle = Middle + 1;
int index = 0;
while(low<=Middle && middle<=High)
{
if(A[low]<=A[middle])
{
B[index] = A[low];
low++;
}
else
{
B[index] = A[middle];
middle++;
}
index++;
}
if(low == Middle+1)
{
for(int i=index;i<=High;i++)
{
B[i] = A[middle];
middle++;
}
}
else
{
for(int i=index;i<=High;i++)
{
B[i] = A[low];
low++;
}
}
for(int i=0;i<=High;i++)
{
A[i] = B[i];
cout<<A[i]<<" ";
}
system("PAUSE");
return 0;
}
#include <stdio.h>
#include <iostream.h>
#include <stdlib.h>
#define Low 0
#define Middle 3
#define High 10
int main(void)
{
int A[High+1] = {2,11,45,57,3,6,13,24,25,65,68};
int B[High+1] = {0,0,0,0,0,0,0,0,0,0,0};
int low = 0;
int middle = Middle + 1;
int index = 0;
while(low<=Middle && middle<=High)
{
if(A[low]<=A[middle])
{
B[index] = A[low];
low++;
}
else
{
B[index] = A[middle];
middle++;
}
index++;
}
if(low == Middle+1)
{
for(int i=index;i<=High;i++)
{
B[i] = A[middle];
middle++;
}
}
else
{
for(int i=index;i<=High;i++)
{
B[i] = A[low];
low++;
}
}
for(int i=0;i<=High;i++)
{
A[i] = B[i];
cout<<A[i]<<" ";
}
system("PAUSE");
return 0;
}