Home > Software engineering >  Failed to recognize number sorting array at new array in JAVA
Failed to recognize number sorting array at new array in JAVA

Time:11-07

I am having a trouble when it is starting to sort the array in chronological number, first and foremost, I built a 2 scanner array that will merge in the final line but it resulted a mess and the last line character line were flashed a 0

Here is my source code:

import java.util.*;
 
public class Main
{
   public static void main(String[] args) 
   {
      Scanner x = new Scanner (System.in);
      System.out.print("Enter the number of elements of the first array: ");
      int first = x.nextInt();
      int ffinal[] = new int[first];

      for(int i=0;i<ffinal.length;i  )
      {
         System.out.print("");
         ffinal[i]=x.nextInt();
      }

      System.out.print("Enter the number of elements of the second array: ");
      int second = x.nextInt();
      int sfinal[] = new int[second];

      for(int i=0;i<sfinal.length;i  )
      {
         System.out.print("");
         sfinal[i]=x.nextInt();
      }
      
      int n = ffinal.length;
      int m = sfinal.length;

      int res[] = new int [n m];

      int i = 0, j=0, k=0;
      while(i< n && j<m )
      {
         if(ffinal[i] <= sfinal[j])
         {
            res[k]=ffinal[i];
            i =1;
            k =1;
         }
         else
         {
            res[k]=sfinal[j];
            j =1;
            k =1;
         }
      }
   
      System.out.print("New array:");
      for (i=0; i<n m;i  )
      {
         System.out.print(" " res[i]); 
      }
    
   }
}

Output:

Enter the number of elements of the first array: 3
2 3 10
Enter the number of elements of the second array: 2
10 16
New array: 2 3 10 0 0

Expected Output:

Enter the number of elements of the first array: 3
2 3 10
Enter the number of elements of the second array: 2
10 16
New array: 2 3 10 10 16

CodePudding user response:

The issue is with your while condition while(i< n && j<m ).
Suppose all your elements of 1st array is smaller than 2nd array, after adding those to the new array, i will be equal to n, so the condition i<n in while(i< n && j<m ) becomes false and exits the loops.
The elements of 2nd array is not added to the new array.

Assume your a1[] = {1,2} and a2[] = {3,4,5}.
n is 2 and m is 3.
as per your code, 1 and 2 will be added to new array a3[].
now i will become 2 while j is still 0.

In this while(i< n && j<m ), i<n which is 2<2 is false. So the while-loop will stop.
Then what about the elements of array a2? {3,4,5} is not added to new array a3.

You can do as @UnholySheep suggested. If you want to continue with yours,
I've corrected your code.

int i = 0, j=0, k=0;
while(i< n || j<m )
{   
    if(i<n && i<m)
    {
        if(ffinal[i] <= sfinal[j])
        {
            res[k]=ffinal[i];
            i =1;
            k =1;
        }
        else
        {
            res[k]=sfinal[j];
            j =1;
            k =1;
        }
    }
    else if(i<n)
    {
        res[k]=ffinal[i];
        i =1;
        k =1;
    }
    else
    {
        res[k]=sfinal[j];
        j =1;
        k =1;
    }
}

CodePudding user response:

import java.util.*;
public class Main {
   public static void main(String[] args) {

      Scanner x = new Scanner (System.in);

      System.out.print("Enter the number of elements of the first array: ");
      int first = x.nextInt();
      int a[] = new int[first];
      
      for(int i=0;i<a.length;i  )
      {
         System.out.print("");
         a[i]=x.nextInt();
      }
      
      System.out.print("Enter the number of elements of the second array: ");
      int second = x.nextInt();
      int b[] = new int[second];
      
      for(int i=0;i<b.length;i  )
      {
         System.out.print("");
         b[i]=x.nextInt();
      }
     
      int j = 0, k = 0;
      int c [] = new int[a.length b.length];
  
      for (int i = 0; i < c.length; i  ) 
      {
         if (j < a.length && k < b.length) 
         {
            if (b[k] < a[j])
            {
               c[i] = b[k];
               k  ;
            }
            else 
            {
               c[i] = a[j];
               j  ;
            }       
         }
            else if (k < b.length) 
            {
              c[i] = b[k];
              k  ;
            }
            else 
            {
              c[i] = a[j];
              j  ;
            }
      }
      System.out.print("New array: ");
      for(int i = 0; i < c.length; i  )
         {
            System.out.print(c[i] " ");
         }
  }
}

Thank you I answered it!

CodePudding user response:

I would separate the code that perform the merge from the input parsing, it will make the code more testable, furthermore, this request the two input arrays to be sorted.

import java.util.Objects;
public class MyClass {
    
    public static int[] merge(int[] first, int[] second) {
        //Check that the input are not null
        Objects.requireNonNull(first, "First array cannot be null");
        Objects.requireNonNull(first, "Second array cannot be null");            // duplicates are allowed so the result size is known up-front
        int[] result = new int[first.length   second.length];
        // cursor over the three arrays, starting from the beginning
        int f = 0;
        int s = 0;
        int r = 0;
        //loop over first array until is complete
        for (; f != first.length;   r) {
            if (s == second.length) {
            //if nothing left in the second array, let's copy everything
            //from first into result and return
                while (f != first.length) {
                    result[r] = first[f];
                      f;
                      r;
                }
                return result;
            }
            // let's copy the smaller of the two into result
            if (second[s] < first[f]) {
                result[r] = second[s];
                  s;
            } else {
                result[r] = first[f];
                  f;
            }
        }
        //we complete the loop over first, let's copy everything left from
        //second to result
        while (s != second.length) {
            result[r] = second[s];
              s;
              r;
        }
        return result;
    }
    
    //use JUnit instead, I am using an online compiler and
    // I cannot bring dependencies in
    public static void check(int[] a, int[] b) {
        assert(a.length == b.length);
        for (int i = 0; i < a.length; i  )
            assert(a[i] == b[i]);
    }
    
    public static void main(String args[]) {
        check(new int[]{2, 3, 10, 10, 16}, merge(new int[]{2, 3, 10}, new int[]{10, 16}));
        check(new int[]{2, 3, 10}, merge(new int[]{2, 3, 10}, new int[]{}));
        check(new int[]{10, 16}, merge(new int[]{}, new int[]{10, 16}));
        check(new int[]{2, 3, 5, 10, 10, 16}, merge(new int[]{2, 3, 10}, new int[]{5, 10, 16}));
    }
}

CodePudding user response:

Look at the trace here for your code

n:2, m:3

i:0,j:0,k:0 | first array 2 3 | second array 10 16 | New array: 0 0 0 0 0
i:1,j:0,k:1 | first array 2 3 | second array 10 16 | New array: 2 0 0 0 0
i:2,j:0,k:2 | first array 2 3 | second array 10 16 | New array: 2 3 0 0 0

At the end of the loop, i has the value 2

In while loop condition while(i< n && j<m ), i<n -> 2<2 will give false and the condition fails and exits the loop.

but as you can see there are elements still remaining in second array so what you need to do is add two additional loops.

import java.util.*;
 
public class Main
{
   public static void main(String[] args) 
   {
      Scanner x = new Scanner (System.in);
      System.out.print("Enter the number of elements of the first array: ");
      int first = x.nextInt();
      int ffinal[] = new int[first];

      for(int i=0;i<ffinal.length;i  )
      {
         System.out.print("");
         ffinal[i]=x.nextInt();
      }

      System.out.print("Enter the number of elements of the second array: ");
      int second = x.nextInt();
      int sfinal[] = new int[second];

      for(int i=0;i<sfinal.length;i  )
      {
         System.out.print("");
         sfinal[i]=x.nextInt();
      }
      
      int n = ffinal.length;
      int m = sfinal.length;

      int res[] = new int [n m];
      System.out.println();

      int i = 0, j = 0, k = 0;
      while(i < n && j < m )
      {
        
         if(ffinal[i] <= sfinal[j])
         {
            res[k]=ffinal[i];
            i =1;
            k =1;
         }
         else
         {
            res[k]=sfinal[j];
            j =1;
            k =1;
         }

      }
      
      // if there are any remaining elements from any of the two arrays add them to res array
      while(i < n){
        res[k]=ffinal[i];
        i =1;
        k =1;
      }
      
      while(j < m){
        res[k]=sfinal[j];
        j =1;
        k =1;
      }
   
      System.out.print("New array:");
      for (i=0; i<n m;i  )
      {
         System.out.print(" " res[i]); 
      }
    
   }
}

In the above code it first checks i < n -> 2<2 -> false,

it then goes to the next while loop j < m -> 0 < 3 -> true so loop throught elements in second array and add into the res array

  •  Tags:  
  • java
  • Related