I would like to implement a method that takes 2 arrays and returns the one that is lexicographically smaller than the other. I tried to do it according to the definition of lexicographic order, but it does not work. Here is my code:
public boolean lexicoSmaller(ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int m = 1;
int n = list1.size() -1;
while(m <= n)
{
boolean firstFound = true;
for(int i=0; i<m; i++)
{
if(!Objects.equals(list1.get(i), list2.get(i)))
{
firstFound = false;
break;
}
}
if(firstFound && list1.get(m) < list2.get(m)) return true;
m++;
}
return false;
}
The code above doesn't give the right answer.
For example for the inputs 0 5 7 9 14 16 18 23
and 1 3 6 11 12 17 20 22
, the answer should be true, but I got false.
When the two arrays are sorted, we can just check for any i, if array1[i] < array2[i] then array1 is lexicografically smaller then array2.