I am trying to find out the best case time complexity while checking if the given array is unsorted.
I think, this is the fastest way to check if array is sorted or unsorted and the time complexity should be O(n) for this one.
for (i = 0; i < a.length-1; i++) {
if (a[i] < a[i + 1]) {
return true;
} else {
return false;
}
}
Or am I wrong?
Yes this takes O(n)
, and it is as fast as it gets .
Moreover, you need to change this:
for (i = 0; i < a.length; i++)
to this:
for (i = 0; i < a.length - 1; i++)
since you access a[i + 1
and you do not want to go out of bounds. Furthermore, your return statements should be swapped.
The average and worst-case complexity for your algorithm to check if an array is unsorted is O(N)
. But the best-case complexity is O(1)
.
The best case occurs when the first two elements of the array are out of order. This is detected in the first loop iteration, and takes a constant time irrespective of N
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.