Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,911 questions

51,843 answers

573 users

How to merge two sorted arrays by moving smaller values to first array and bigger values to second array in C

2 Answers

0 votes
#include <stdio.h>

void MergeTwoSortedArrays(int arr1[], int arr2[], int size1, int size2) {
    for (int i = size2 - 1; i >= 0; i--) {
        int j, last1 = arr1[size1 - 1];
        for (j = size1 - 2; j >= 0 && arr1[j] > arr2[i]; j--) {
            arr1[j + 1] = arr1[j];
        }
        if (last1 > arr2[i]) {
            arr1[j + 1] = arr2[i];
            arr2[i] = last1;
        }
    }
}

int main()
{
    int arr1[] = { 1, 4, 5, 8, 10, 15, 19, 20 };
    int arr2[] = { 2, 3, 6, 9, 12, 17 };
    
    int size1 = sizeof(arr1) / sizeof(arr1[0]);
    int size2 = sizeof(arr2) / sizeof(arr2[0]);
    
    MergeTwoSortedArrays(arr1, arr2, size1, size2);

    printf("arr1: ");
    for (int i = 0; i < size1; i++)
        printf("%d ", arr1[i]);

    printf("\narr2: ");
    for (int i = 0; i < size2; i++)
        printf("%d ", arr2[i]);

    return 0;
}




/*
run:

arr1: 1 2 3 4 5 6 8 9
arr2: 10 12 15 17 19 20

*/

 



answered Apr 21, 2023 by avibootz
0 votes
#include <stdio.h>
 
void MergeTwoSortedArrays(int arr1[], int arr2[], int size1, int size2) {
    for (int i = 0; i < size1; i++) {
        if (arr1[i] > arr2[0]) {
            // swap 
            int tmp = arr1[i];
            arr1[i] = arr2[0];
            arr2[0] = tmp;
      
            int element0 = arr2[0];
  
            // Move array2[0] to the correct position to maintain the sorted order
            int k;
            for (k = 1; k < size2 && arr2[k] < element0; k++) {
                arr2[k - 1] = arr2[k];
            }
      
            arr2[k - 1] = element0;
        }
    }
}
 
int main()
{
    int arr1[] = { 1, 4, 5, 8, 10, 15, 19, 20 };
    int arr2[] = { 2, 3, 6, 9, 12, 17 };
     
    int size1 = sizeof(arr1) / sizeof(arr1[0]);
    int size2 = sizeof(arr2) / sizeof(arr2[0]);
     
    MergeTwoSortedArrays(arr1, arr2, size1, size2);
 
    printf("arr1: ");
    for (int i = 0; i < size1; i++)
        printf("%d ", arr1[i]);
 
    printf("\narr2: ");
    for (int i = 0; i < size2; i++)
        printf("%d ", arr2[i]);
 
    return 0;
}
 
 
 
 
/*
run:
 
arr1: 1 2 3 4 5 6 8 9 
arr2: 10 12 15 17 19 20 
 
*/

 



answered Sep 16, 2023 by avibootz
...