[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
/** 合并有序数组:
* 给定两个排序后的数组A和B,其中A的末端有足够的缓冲空间容纳B
* 编写一个方法,将B并入A,并排序
*/
思路两种:一步到位 或者 先合并再排序
一步到位:归并的思路,同时倒序遍历a,b两个数组,比较大小,大的值就放到扩建后的数组a中
代码:
#include <bits/stdc++.h> using namespace std; /** 合并有序数组: *
给定两个排序后的数组A和B,其中A的末端有足够的缓冲空间容纳B * 编写一个方法,将B并入A,并排序 * 采用归并思想 */ void f(int a[],
int b[], int alen, int blen) { int sp1 = alen - 1; //指针指向数组a的最后一位 int sp2 =
blen - 1; //指针指向数组a的最后一位 int sp3 = alen + blen - 1; //指针指向两个数组合并后的最后一位
while(sp3 >= 0) { if(a[sp1] > b[sp2]) //从后往前分配数值 a[sp3--] = a[sp1--]; else
if(a[sp1] <= b[sp2]) a[sp3--] = b[sp2--]; } for(int i = 0; i < alen + blen;
i++) cout << a[i] << " "; } int main() { int a[20] = {1, 3, 5, 7, 9}; int b[] =
{2, 4, 6, 8, 10}; int alen = 5; //为图方便直接写了,,方法:用一个for循环遍历数组,结果不为0,sum++;sum为长度
int blen = sizeof(b) / sizeof(int); //这个直接用sizeof求长度就行 f(a, b, alen, blen);
return 0; }
运行结果:
先合并再排序:先用for循环,把b数组合并到a中,再用个sort,排序数组a,结束。
代码:
void f(int a[], int b[], int alen, int blen) { for(int i = 0; i < blen; i++) {
a[alen + i] = b[i]; } sort(a,a+alen+blen); //只对存储数据的部分进行排序 for(int i = 0; i <
alen + blen; i++) cout << a[i] << " "; }
结果一样
仅以此题纪念一下,当初刚学时,遇到数组问题就一脸懵逼的我。。。再者,顺带复习下归并排序叭