实验报告->数组的定义和使用->两路合并法合并两个升序数组

来源:互联网 发布:淘宝超级搜索 编辑:程序博客网 时间:2024/05/22 02:24

/*
用“两路合并法”把两个已按升序排列的数组合并成一个升序数组。例如:a数组内容为1、3、4、7、9、11、15,b数组为2、5、6、8、12、13、19,合并后的结果为1、2、3、4、5、6、7、8、9、11、12、13、15、19。
*/

#include <stdio.h>//数组打印函数void Print(int *x, int N){    int i;    for(i=0; i<N; i++)    {        printf("%-3d", x[i]);    }    printf("\n");}//数组合并函数void Merge_function(int *str1, int *str2){    int M= 14;    int out[M];//输出数组    int i=0, j=0, k=0;    while (i<7 && j<7){        //循环将较小元素放入C        if (str1[i]<str2[j])        {            out[k]=str1[i];            i++;            k++;        }        else{            out[k]=str2[j];            j++;            k++;        }    }//while    if(i==7){    //第1个数组元素已经全部放到C中,将第2个数组剩余元素全放到C中        while (j<7)        {            out[k]=str2[j];            k++;            j++;        }    }    if(j==7){    //第2个数组元素已经全部放到C中,将第1个数组剩余元素全放到C中        while (i<7)        {        out[k]=str1[i];            k++;            i++;        }    }    printf("两个数组合并之后:\n");    Print(out, M);}void main(){    int N = 7;    int a[] = {1, 3, 4, 7, 9, 11, 15};    int b[] = {2, 5, 6, 8, 12, 13, 19};    printf("a数组合并之前:\n");    Print(a, N);    printf("b数组合并之前:\n");    Print(b, N);    //调用数组合并函数    Merge_function(a, b);}
阅读全文
0 0
原创粉丝点击