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 Java

2 Answers

0 votes
import java.util.Arrays;

public class MyClass {
    public static void merge_sorted_not_equal_arrays(int[] array1, int[] array2) {
        int size1 = array1.length;
        int size2 = array2.length;
 
        for (int i = 0; i < size1; i++) {
            if (array1[i] > array2[0]) {
                // swap 
                int tmp = array1[i];
                array1[i] = array2[0];
                array2[0] = tmp;
 
                int element0 = array2[0];
 
                // Move array2[0] to the correct position to maintain the sorted order
                int k;
                for (k = 1; k < size2 && array2[k] < element0; k++) {
                    array2[k - 1] = array2[k];
                }
 
                array2[k - 1] = element0;
            }
        }
    }
    public static void main(String args[]) {
        int[] array1 = { 1, 4, 6, 8, 10 };
        int[] array2 = { 2, 3, 5, 9 };
 
        merge_sorted_not_equal_arrays(array1, array2);
 
        System.out.println(Arrays.toString(array1));
        System.out.println(Arrays.toString(array2));
    }
}




/*
run:

[1, 2, 3, 4, 5]
[6, 8, 9, 10]

*/

 



answered Sep 16, 2023 by avibootz
edited Sep 16, 2023 by avibootz
0 votes
import java.util.Arrays;

public class MyClass {
    public static void merge_sorted_not_equal_arrays(int[] array1, int[] array2) {
        int size1 = array1.length;
        int size2 = array2.length;
        
        for (int i = size2 - 1; i >= 0; i--) {
            int 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;
            }
        }
    }
    public static void main(String args[]) {
        int[] array1 = { 1, 4, 6, 8, 10 };
        int[] array2 = { 2, 3, 5, 9 };
 
        merge_sorted_not_equal_arrays(array1, array2);
 
        System.out.println(Arrays.toString(array1));
        System.out.println(Arrays.toString(array2));
    }
}




/*
run:

[1, 2, 3, 4, 5]
[6, 8, 9, 10]

*/

 



answered Sep 16, 2023 by avibootz
...