Merge two number array - C Array

C examples for Array:Array Value

Description

Merge two number array

Demo Code

#include <stdio.h>

int merge(int[], int, int[], int, int[]);

int main () {//from   ww  w. jav  a2s  . co  m
    
    int A[] = {2, 8, 5, 4, 6, 7};
    int B[] = {6, 5, 7, 4};
    int C[20];
    int n = merge(A, 6 , B, 4, C);
    
    for (int i = 0; i < n; i++) 
       printf("%d \n", C[i]);
   
}

int merge(int A[], int m, int B[], int n, int C[]) {
    int i = 0; //i points to the first (smallest) number in A
    int j = 0; //j points to the first (smallest) number in B
    int k = -1; //k will be incremented before storing a number in C[k]
 
    while (i < m && j < n) {
        if (A[i] < B[j]) C[++k] = A[i++];
        else C[++k] = B[j++];
    }
 
    if (i == m) ///copy B[j] to B[n-1] to C
        for ( ; j < n; j++) C[++k] = B[j];
    else 
        for ( ; i < m; i++) C[++k] = A[i];
    return m + n;
}

Related Tutorials