In: Computer Science
Write a linear-search Java method to test if a String array is already sorted alphabetically. The prototype should be static boolean ifsorted(String [] s)
{
}
Here we are iterating over the string array s, checking whether the adjacent element is in right order or not. compareTo() method is used to get the difference between the current element and the adjacent element. This method returns integer value to define whether the adjacent element is greater than or equal to or smaller than the current element.
compareTo() returns:
0 : if both the elements are in same order.
1: if greater than the adjacent element
-1 : if smaller than the adjacent element
In this method we are checking whether the integer value returned by the compareTo() function is equal to 1. If yes, then it is clear that the current element is greater than the adjacent element. Hence, the array is not sorted.
static boolean ifsorted(String[] s){
for(int i=0;i<s.length-1;i++){
if(s[i].compareTo(s[i+1])==1){
return false;
}
}
return true; // returns true if the array is sorted
}