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,870 questions

51,793 answers

573 users

How to merge elements of two sorted not equal arrays by maintaining the sorted order in Node.js

2 Answers

0 votes
function merge_sorted_not_equal_arrays(array1, array2) {
    let size1 = array1.length;
    let size2 = array2.length;
    
    for (let i = 0; i < size1; i++) {
        if (array1[i] > array2[0]) {
            // swap 
            let tmp = array1[i];
            array1[i] = array2[0];
            array2[0] = tmp;
                
            let element0 = array2[0];
            let k = 1
            for (; k < size2 && array2[k] < element0; k++) {
                array2[k - 1] = array2[k];
            }
            array2[k - 1] = element0;
        }
    }
}

const array1 = [1, 4, 6, 8, 10];
const array2 = [2, 3, 5, 9];

merge_sorted_not_equal_arrays(array1, array2);

console.log(array1);
console.log(array2);




/*
run:
 
[ 1, 2, 3, 4, 5 ]
[ 6, 8, 9, 10 ]

*/

 



answered Sep 16, 2023 by avibootz
0 votes
function merge_sorted_not_equal_arrays(array1, array2) {
    let size1 = array1.length;
    let size2 = array2.length;
    
    for (let i = size2 - 1; i >= 0; i--) {
        let j, last1 = array1[size1 - 1];
        for (j = size1 - 2; j >= 0 && array1[j] > array2[i]; j--) {
            array1[j + 1] = array1[j];
        }
        if (last1 > array2[i]) {
            array1[j + 1] = array2[i];
            array2[i] = last1;
        }
    }
}

const array1 = [1, 4, 6, 8, 10];
const array2 = [2, 3, 5, 9];

merge_sorted_not_equal_arrays(array1, array2);

console.log(array1);
console.log(array2);




/*
run:
 
[ 1, 2, 3, 4, 5 ]
[ 6, 8, 9, 10 ]

*/

 



answered Sep 16, 2023 by avibootz
...