check if first array is sorted and if there are consecutive duplicate elements check second array at the index of duplicate elements

Tags: ,



We need to check if the first array is sorted, and if there are consecutive duplicate elements, check the second array at the index of duplicate elements. This is my code and output

The output I expect is false since a[2]=a[3] and thus we should move to the 2nd array and there b[2]>b[3].

for ex: 1.

array1[]={1,2,3,4,5};
array2[]={5,6,4,3,2};

this should return true because the first array is sorted

2.

array1[]={1,2,3,3,4};
array2[]={5,4,3,6,2};

this should also return true since array1[2]=array1[3] then we go to the array2 and there array2[2]<array2[3] and hence it should return true.

3.

array1[]={1,2,3,3,4};
array2[]={5,4,4,4,2};

this should also return true since array1[2]=array1[3] then we go to the array2 and there array2[2]=array2[3] and hence it should return true.

4.

array1[]={1,2,3,3,4};
array2[]={5,6,4,3,2};

this should also return false since array1[2]=array1[3] then we go to the array2 and there array2[2]>array2[3] and hence it should return false.

Answer

In your case (4) it return true, because in your code you have if (a [i] < a[i+1]) return true inside the loop that check the duplicated values. So in array1 (1 < 2) is true, hence it return true. How to solve this issue, you have to divide your code in two parts.

    1. check if the first array is sorted a good explanation is in stackoverflow.com/a/19458302/3429103,
    1. your code to complete the verification of same value successive and check in the second array.

something like

public class Main
{
    public static boolean isSorted(int[] a) 
    {
        for (int i = 0; i < a.length - 1; i++) {
            if (a[i] > a[i + 1]) 
            {
                return false;
            }
        }

        return true;
    }
    
    public static boolean checkDuplicate(int[] a, int b[]) 
    {
        for (int i = 0; i < a.length - 1; i++) 
        {
            if (a[i] == a[i + 1] && b[i] > b[i + 1]) 
            {
                return false;
            }
        }

        return true;
    }
    
    public static void main(String[] args) 
    { 
        int array1[]={1,2,3,3,4}; 
        int array2[]={5,6,4,3,2};
        
        if(isSorted(array1) && checkDuplicate(array1,array2))
            System.out.println("True");
        else
            System.out.println("False");
    }
}


Source: stackoverflow