本文主要是介绍【王道数据结构】【chapter8排序】【P391t2】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
设顺序表用数组A[]表示,表中元素存储在数组下标1~m+n的范围内,前m个元素递增有序,后n个元素递增有序,设计一个算法,使得整个顺序表有序
#include <iostream>
#include <time.h>
#include <stdlib.h>int * buildarray(int s1,int s2)
{int * tmp=(int*) malloc(sizeof (int)*(s1+s2+1));int record=0;for(int i=1;i<=s1;i++) record=record+rand()%3,tmp[i]=record;record=2;for(int i=s1+1;i<=s1+s2;i++) record=record+rand()%5,tmp[i]=record;return tmp;
}void print(int * tmp,int size)
{for(int i=1;i<=size;i++) printf("%3d",tmp[i]);puts("");
}void merge(int * tmp,int s1,int s2)
{int * b=(int *) malloc(sizeof (int)*(s1+s2+1));for(int i=1;i<=s1+s2;i++)b[i]=tmp[i];int l=1,r=s1+1,pointer=1;while(l<=s1&&r<=s1+s2){if(b[l]<=b[r]) tmp[pointer++]=b[l++];else tmp[pointer++]=b[r++];}while(l<=s1) tmp[pointer++]=b[l++];while(r<=s1+s2) tmp[pointer++]=b[r++];
}
int main() {srand(time(nullptr));int s1=20,s2=7;int *r1= buildarray(s1,s2);print(r1,s1+s2);merge(r1,s1,s2);print(r1,s1+s2);return 0;
}
这篇关于【王道数据结构】【chapter8排序】【P391t2】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!