Home > Net >  fusion of 2 arrays sorted in a third (java)
fusion of 2 arrays sorted in a third (java)

Time:01-24

i have to fusion 2 arrays previously sorted. For now I requested the dimensions of the arrays, I instantiated the arrays, then I did a for to populate them and I added the sorting of the arrays

    package pFusioneVettoriCacciola;
import java.util.*;

public class Fusione {

    public static void main(String[] args) {
    Scanner tastiera = new Scanner (System.in);
    
    //variabili
    int m=0;
    int n=0;
    int i=0;
    int j=0;
    int f=0;
    int l=0;
    int k = 0;
    int scambio = 0;
    boolean controllo = true;
    int [] vett1;
    int [] vett2;
    int [] fusione;


    //grandezze vettori
        do {
            System.out.println("Inserire grandezza del primo vettore");
            m = tastiera.nextInt();
            if (m<=0)
            {
                System.out.println("Grandezza non valida reinserire ");
            }
        }while(m<=0);
        do {
            System.out.println("Inserire grandezza del secondo vettore");
            n = tastiera.nextInt();
            if (n<=0)
            {
                System.out.println("Grandezza non valida reinserire ");
            }
        }while(n<=0);
        
        //istanzazioni vettori
    vett1= new int [m];
    vett2= new int [n];
    fusione= new int [m n];
    
        //popolamento vettore uno
        
        for ( i = 0; i < vett1.length; i  ) 
        {
        System.out.println("Inserire valore della cella "   i   " (Primo  Vettore)" );
        vett1[i]= tastiera.nextInt();
        }
        
        //popolamento vettore due
        
        for ( i = 0; i < vett2.length; i  ) 
        {
        System.out.println("Inserire valore della cella "   i   " (Secondo Vettore)");
        vett2[i]= tastiera.nextInt();
        }
        
        //stampa primo vettore non ordinato
        
        System.out.println("Stampa primo vettore (non ordinato):");
        for ( i = 0; i < vett1.length; i  ) 
        {
            System.out.println(vett1[i]);
        }
        
        //stampa secondo vettore non ordinato
        
        System.out.println("Stampa secondo vettore (non ordianto):");
        for ( i = 0; i < vett2.length; i  ) 
        {
            System.out.println(vett2[i]);
        }
        
        //ordinamento primo vettore
        
        for (i = 0; i < (vett1.length-1) ; i  ) 
        {
            for ( j = 0; j < (vett1.length-1)-i; j  )
            {
                
                if (vett1[j] > vett1[j 1])
                {
                    scambio = vett1[j];
                    vett1[j] = vett1[j 1];
                    vett1[j 1] =scambio;
                }
            }
        }
        
        //ordinamento secondo vettore
        
        for (i = 0; i < (vett2.length-1) ; i  ) 
        {
            for ( j = 0; j < (vett2.length-1)-i; j  )
            {
                
                if (vett2[j] > vett2[j 1])
                {
                    scambio = vett2[j];
                    vett2[j] = vett2[j 1];
                    vett2[j 1] =scambio;
                }
            }
        }
        
        //stampa primo vettore ordinato
        
        System.out.println("Stampa primo vettore (ordinato):");
        for ( i = 0; i < vett1.length; i  ) 
        {
            System.out.println(vett1[i]);
        }
        
        //stampa secondo vettore ordinato
        
        System.out.println("Stampa secondo vettore (ordianto):");
        for ( i = 0; i < vett2.length; i  ) 
        {
            System.out.println(vett2[i]);
        }


        //fusione
        


          //Print Vettore fuso
        
        System.out.println("Ecco il vettore fuso:");
        for ( i = 0; i < fusione.length; i  ) 
        {
            System.out.println(fusione[i]);
        }
        
}
}

CodePudding user response:

I am assuming that by "fusion" you meant "merge". Since this is for school, I am assuming making use of utility classes is out of the question. But I will show you both ways.

To merge arrays

crude (brute force) way
int[] a = {1,3,5};
int[] b = {2,4,6};
int[] dest = new int[a.length   b.length];

for (int i = 0; i < a.length; i  ) {
    dest[i] = a[i];
}

for (int i = 0; i < b.length; i  ) {
    dest[i] = b[i];
}
Using System class
int[] a = {1,3,5};
int[] b = {2,4,6};
int[] dest = new int[6];
System.arraycopy(a, 0, dest, 0, 3);
System.arraycopy(b, 0, dest, 3, 3);

The arguments in arraycopy function are: Object src, int srcPos, Object dest, int destPos, int length. In this case, the src is the original array (a or b), the srcPos is always 0 because you want to copy the entire (source) array, and the dest is the array you are copying to.

To copy the first array (a), you will indicate the destPos to be 0 and the length is the length of your original array. For this example, the length for both original arrays is 3. For the second example, the starting index is 3 because index positions 0, 1, and 2, contain the values from the first array.

To sort the array

Once you have the arrays merged, then you need to sort the destination array. Sorting can be easily done using Arrays.sort() method:

Arrays.sort(dest);

This function returns void, but it saves the sorted array back in the array passed to the function. For you, this is not acceptable I am guessing. So, you will need your own sorting algorithm. One popular sorting algorithm used in schools is "Bubble Sort".

int n = dest.length;
int temp = 0;
for (int i = 0; i < n; i  ) {
    for (int j = 1; j < (n - i); j  ) {
        if (dest[j - 1] > dest[j]) {
            // swap elements
            temp = dest[j - 1];
            dest[j - 1] = dest[j];
            dest[j] = temp;
        }
    }
}

One-loop solution for merging (update)

If the original arrays are of the same length, you could simplify the merging in a single loop using a scheme something like this:

int[] dest = new int[a.length   b.length];
int ptrOffset = a.length;

for (int i = 0; i < a.length; i  , ptrOffset  ) {
    dest[i] = a[i];
    dest[ptrOffset] = b[i];
}

Because the arrays are of the same length, you could pick either array arbitrarily to determine the limit to the number of iterations. In the above example, I picked array a. Then, I calculated the pointer offset of where I needed to start copying the contents of array b to. I called that ptrOffset. That allowed me to simultaneously copy the contents of both arrays into the destination array. This solution only works if both arrays are of equal length.

CodePudding user response:

The answer by hfontanez is correct. I just want to add that Stream API can be very handy for such a purpose.

With streams, you start by creating a stream of arrays and then applying flatMap and sorting. After that, all the elements are ready to be packed into a single array.

Merge two arrays like this:

public static int[] mergeArrays(int[] first, int[] second) {
        return IntStream.concat(IntStream.of(first), IntStream.of(second))
                .sorted()
                .toArray();
    }

This method allows to combine of any number of arrays:

    public static int[] mergeAllArrays(int[]... arrays) {
        return Stream.of(arrays)
                .flatMapToInt(IntStream::of)
                .sorted()
                .toArray();
    }

main

public static void main(String[] args) {
        int[] arr1 = {1, 2, 3};
        int[] arr2 = {4, 5, 6};
        int[] arr3 = {10, 20, 30};

        System.out.println(Arrays.toString(mergeArrays(arr1, arr2)));
        System.out.println(Arrays.toString(mergeAllArrays(arr3, arr1, arr2)));
    }

OUTPUT

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 10, 20, 30]

CodePudding user response:

Since you only want to use one for loop, it will be bit cumbersome on your if conditions. I have shared the implementation below:

public class Fusione {

    public static void main(String[] args) {
        Scanner tastiera = new Scanner(System.in);

        // variabili
        int m = 0;
        int n = 0;
        int i = 0;
        int j = 0;
        int f = 0;
        int l = 0;
        int k = 0;
        int scambio = 0;
        boolean controllo = true;
        int[] vett1;
        int[] vett2;
        int[] fusione;

        // grandezze vettori
        do {
            System.out.println("Inserire grandezza del primo vettore");
            m = tastiera.nextInt();
            if (m <= 0) {
                System.out.println("Grandezza non valida reinserire ");
            }
        } while (m <= 0);
        do {
            System.out.println("Inserire grandezza del secondo vettore");
            n = tastiera.nextInt();
            if (n <= 0) {
                System.out.println("Grandezza non valida reinserire ");
            }
        } while (n <= 0);

        // istanzazioni vettori
        vett1 = new int[m];
        vett2 = new int[n];
        fusione = new int[m   n];

        // popolamento vettore uno

        for (i = 0; i < vett1.length; i  ) {
            System.out.println("Inserire valore della cella "   i   " (Primo  Vettore)");
            vett1[i] = tastiera.nextInt();
        }

        // popolamento vettore due

        for (i = 0; i < vett2.length; i  ) {
            System.out.println("Inserire valore della cella "   i   " (Secondo Vettore)");
            vett2[i] = tastiera.nextInt();
        }

        // stampa primo vettore non ordinato

        System.out.println("Stampa primo vettore (non ordinato):");
        for (i = 0; i < vett1.length; i  ) {
            System.out.println(vett1[i]);
        }

        // stampa secondo vettore non ordinato

        System.out.println("Stampa secondo vettore (non ordianto):");
        for (i = 0; i < vett2.length; i  ) {
            System.out.println(vett2[i]);
        }

        // ordinamento primo vettore

        for (i = 0; i < (vett1.length - 1); i  ) {
            for (j = 0; j < (vett1.length - 1) - i; j  ) {

                if (vett1[j] > vett1[j   1]) {
                    scambio = vett1[j];
                    vett1[j] = vett1[j   1];
                    vett1[j   1] = scambio;
                }
            }
        }

        // ordinamento secondo vettore

        for (i = 0; i < (vett2.length - 1); i  ) {
            for (j = 0; j < (vett2.length - 1) - i; j  ) {

                if (vett2[j] > vett2[j   1]) {
                    scambio = vett2[j];
                    vett2[j] = vett2[j   1];
                    vett2[j   1] = scambio;
                }
            }
        }

        // stampa primo vettore ordinato

        System.out.println("Stampa primo vettore (ordinato):");
//      for (i = 0; i < vett1.length; i  ) {
//          System.out.println(vett1[i]);
//      }
        System.out.println(Arrays.toString(vett1));
        // stampa secondo vettore ordinato

//      System.out.println("Stampa secondo vettore (ordianto):");
//      for (i = 0; i < vett2.length; i  ) {
//          System.out.println(vett2[i]);
//      }

        System.out.println(Arrays.toString(vett2));
        // fusione
         k =0;
         i =0 ; 
         j =0; 
        while ( k < fusione.length)
        {
            
            if ( i < vett1.length &&  j <vett2.length && vett1[i] <= vett2[j] )
            {
                fusione[k  ] = vett1[i  ];
            }
            else if( j < vett2.length &&  i < vett1.length && vett1[i] > vett2[j]) {
                fusione[k  ] = vett2[j  ];
            }
            else if(i == vett1.length && j < fusione.length )
            {
                fusione[k  ] = vett2[j  ];
            }
            else if ( j == vett2.length && i < fusione.length)
            {
                fusione[k  ] = vett1[i  ];
            }
        }
        // Print Vettore fuso

        System.out.println("Ecco il vettore fuso:");
//      for (i = 0; i < fusione.length; i  ) {
//          System.out.println(fusione[i]);
//      }
        System.out.println(Arrays.toString(fusione));
    }
}

This gives the output as expected:

Inserire grandezza del primo vettore
2
Inserire grandezza del secondo vettore
3
Inserire valore della cella 0 (Primo  Vettore)
9
Inserire valore della cella 1 (Primo  Vettore)
8
Inserire valore della cella 0 (Secondo Vettore)
6
Inserire valore della cella 1 (Secondo Vettore)
5
Inserire valore della cella 2 (Secondo Vettore)
4
Stampa primo vettore (non ordinato):
9
8
Stampa secondo vettore (non ordianto):
6
5
4
Stampa primo vettore (ordinato):
[8, 9]
[4, 5, 6]
Ecco il vettore fuso:
[4, 5, 6, 8, 9]
  •  Tags:  
  • Related