在C中合并多个排序的数组

前端之家收集整理的这篇文章主要介绍了在C中合并多个排序的数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试合并8个预先排序的数组.我对C很新,但这是我到目前为止所提出的.不用说它不起作用.我无法弄清楚的是为什么.我已经将它基于C mergesort实现 here并尝试将其扩展到8维并稍微简化它,但由于某种原因它倾向于给我第一个数组的元素,然后是34,30然后它重复23直到最后.它甚至没有发现21是第一次迭代的最小值.
int test1[5] = {23,24,25,33,51};
int test2[5] = {21,34,44,50,62};
int test3[5] = {34,36,41,46};
int test4[5] = {30,31,32,35,40};
int test5[5] = {54,56,57,58,60};
int test6[5] = {31,51,52};
int test7[5] = {44,46,76,78,79};
int test8[5] = {23,43,54,63};

int output[40];
int t1,t2,t3,t4,t5,t6,t7,t8;
t1 = 0;
t2 = 0;
t3 = 0;
t4 = 0;
t5 = 0;
t6 = 0;
t7 = 0;
t8 = 0;
int p = 0;
int temp1;
int temp2;

while(p < 40) {
    if (t1 < 5) {
        temp1 = 1;
        temp2 = test1[t1];
    }else if (test2[t2] <= test1[t1] && t2 < 5) {
        temp1 = 2;
        temp2 = test2[t2];
    }else if (test3[t3] <= temp2 && t3 < 5) {
        temp1 = 3;
        temp2 = test3[t3];
    }else if (test4[t4] <= temp2 && t4 < 5) {
        temp1 = 4;
        temp2 = test4[t4];
    }else if (test5[t5] <= temp2 && t5 < 5) {
        temp1 = 5;
        temp2 = test5[t5];
    }else if (test6[t6] <= temp2 && t6 < 5) {
        temp1 = 6;
        temp2 = test6[t6];
    }else if (test7[t7] <= temp2 && t7 < 5) {
        temp1 = 7;
        temp2 = test7[t7];
    }else if (test8[t8] <= temp2 && t8 < 5) {
        temp1 = 8;
        temp2 = test8[t8];
    }
    switch(temp1) {
        case 1:
            output[p] = temp2;
            t1++;
            break;
        case 2:
            output[p] = temp2;
            t2++;
            break;
        case 3:
            output[p] = temp2;
            t3++;
            break;
        case 4:
            output[p] = temp2;
            t4++;
            break;
        case 5:
            output[p] = temp2;
            t5++;
            break;
        case 6:
            output[p] = temp2;
            t6++;
            break;
        case 7:
            output[p] = temp2;
            t7++;
            break;
        case 8:
            output[p] = temp2;
            t8++;
            break;
    }
    printf("%d\n",output[p]);
    p++;
}

谢谢你尽你所能的帮助.

解决方法

这就是你获得第一个数组的前5个元素的原因:
if (t1 < 5) {
        temp1 = 1;
        temp2 = test1[t1];

您的代码专门确保首先选择第一个数组的前5个元素.您应该将test1中的下一个元素的值与其他数组中的下一个元素进行比较,而不是盲目地选择它.另外,你使用if..then..else if .. else if …是不正确的.如果你发现数组2的下一个元素小于数组1的下一个元素,你仍然需要检查数组3,4和5是否更少.

尝试像这样构建代码

int temp1 = -1;
if (t1 < 5) {
    temp1=1;
    temp2=test1[t1];
}
if ((t2 < 5) && ((temp1 < 0) || (test2[t2] < temp2))) {
    temp1=2;
    temp2=test2[t2];
}
if (t3...

然后是您现有的switch语句.

原文链接:https://www.f2er.com/c/111105.html

猜你在找的C&C++相关文章