If you have a list or array of elements then how should we determine the given sequence is either sorted in ascending or descending order.
There are many ways of finding it but the following solution provides a solution in one iteration so complexity is O(n).
We need to compare the elements such that either elements are either increasing or decreasing , if this condition is not matching then unsorted sequence otherwise its a sorted sequence.
/**
* @author sachin.srivastava
* @tek9g.blogpspot.com
* {@code checking various scenarios of handling the sorting cases.}
*/
//checking if a list is sorted means asceding or descending in either way.
//complexity is O(n) beacaue of traversal of n elements of the list
public static <T extends Comparable<T>> boolean isSorted(List<T> list) {
if(list == null || list.isEmpty()){
return false;
}
if(list.size() == 1) {
return true;
}
T prev =null;
boolean asc = true;
boolean desc = true;
for (T t : list) {
//ascending
if(prev!=null && prev.compareTo(t) > 0 ){
asc = false;
}
//descending
if(prev!=null && prev.compareTo(t) < 0 ){
desc = false;
}
prev = t;
}
return asc || desc;
}
Testcases :
System.out.println(isSorted(Arrays.asList(1,2,4,5)));//true
System.out.println(isSorted(Arrays.asList(5,2,4,5)));//false
System.out.println(isSorted(Arrays.asList("abc","bcd","def","fgh")));//true
System.out.println(isSorted(Arrays.asList("b","a","c","d")));//false
Enjoy the coding !!!!
No comments:
Post a Comment