假设这9个已经从小到大有序的数组分别为a1、a2、a3、a4、a5、a6、a7、a8、a9,每个数组中包含n个元素。现在要将一个新数据x插入到这些数组中。

  1. 遍历这9个数组,找到第一个比x大的元素所在的位置,记为pos。若没有找到,则pos=n。

  2. 将pos及其后面的元素都往后移动一个位置,腾出位置给x。

  3. 将x插入到pos所在的位置。

代码实现如下:

int n = // 数组中元素个数
int x = // 要插入的新数据

int* a[9] = { a1, a2, a3, a4, a5, a6, a7, a8, a9 }; // 存储9个数组的指针

for (int i = 0; i < 9; i++) {
    int* p = a[i];
    int pos = 0;
    while (pos < n && *(p+pos) < x) {
        pos++;
    }
    for (int j = n-1; j >= pos; j--) {
        *(p+j+1) = *(p+j);
    }
    *(p+pos) = x;
}
``
输入9个已经从小到大有序的数组要求输入一个新数据将此数按照原来的规律插入到数组中

原文地址: https://www.cveoy.top/t/topic/eEwY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录