题目:设有2个长度不等的有序表,各表中元素按升序排列,要求通过两两合并的方法把2个表合并成一个升序表,要求在最坏的情况下比较的次数较少,请给出具体的策略。例如: 表1:1,3,16 表2:2,5,9,11,17,47
解题思路:
方法一:用Merge方法,没有用贪婪法;
方法二:用GreedMerge方法,贪婪算法,思路如下:
比如对数组a{1,3,16}和数组b{2,5,9,11,17,47},构建最终合并的数组d,长度为两个数组长度之和
假设将b数组插入到a中,则d数组初始值应先为数组a的值
然后对数组b取中间值,此题中第一次取中间值为11,与a的最后一个值16比较,若大于16则将11以及11以后的值插入到16后面,若小于16则取数组a的前一个进行比较,此时比较的值为3和11,发现11大于3,此时将11以及后面的数值全部插入到3的后面。
代码:
#include <iostream>
using namespace std;
int* mergeArray(int* a,int a_len,int *b,int b_len){
int* result=new int[a_len+b_len];
int i,j,c;
for( i=0,j=0,c=0;i<a_len&&j<b_len;){
if(a[i]<b[j]){
result[c++]=a[i];
i++;
}else{
result[c++]=b[j];
j++;
}
}
while(i<a_len){
result[c++]=a[i++];
}
while(j<b_len){
result[c++]=b[j++];
}
return result;
}
void GreedMerge(int* a,int a_len,int *b,int b_len){
int len=a_len+b_len;
int* d=new int[len];
int d_len=a_len;//d的实际长度
for(int i=0;i<d_len;i++){
d[i]=a[i];
}
int index=a_len-1;
int high=b_len;
int low=0;
int center=(high+low)/2;
while(low<high&&index>-1){
center=(high+low)/2;
if(b[center]>=a[index]){
for(int j=0;j<high-center;j++){
for(int loop=len-1;loop>index+1;loop--){
d[loop]=d[loop-1];
}
d_len++;
}
for(int loop=0;loop<high-center;loop++){
d[index+1+loop]=b[center+loop];
}
high=center;
}else{
int temp_center=center;
while(center<high&&b[center]<a[index]){
center++;
}
if(center==high){
center=temp_center;
index--;
// cout<<index<<"====================="<<endl;
}else{
for(int j=0;j<high-center;j++){
for(int loop=len-1;loop>index+1;loop--){
d[loop]=d[loop-1];
}
d_len++;
}
for(int loop=0;loop<high-center;loop++){
d[index+1+loop]=b[center+loop];
}
high=center;
}
}
}
if(high!=low){//if(d_len!=len)
int cishu=high-low;//cishu=len-d_len;
for(int i=0;i<cishu;i++){
for(int j=len-1;j>0;j--){
d[j]=d[j-1];
}
}
for(int m=0;m<cishu;m++){
d[m]=b[m];
}
}
for(int k=0;k<len;k++){
cout<<d[k]<<" ";
}
}
int main()
{
int a[3]={1,3,16};
int b[5]={2,5,9,17,25};
int c[3]={5,7,11};
/* int* result=mergeArray(a,3,b,6);
result=mergeArray(result,10,c,3);
for(int i=0;i<13;i++){
cout<<result[i]<<" ";
}*/
GreedMerge(a,3,b,5);
return 0;
}