[英]Best case time Complexity to check if the array is unsorted
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. 我认为,这是检查数组是否已排序的最快方法,对此的时间复杂度应为O(n)。
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 . 是的,这需要O(n)
,并且它要快得多 。
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. 因为您访问a[i + 1
并且您不想超出范围。 Furthermore, your return statements should be swapped. 此外,应该交换您的return语句。
The average and worst-case complexity for your algorithm to check if an array is unsorted is O(N)
. 用于检查数组是否未排序的算法的平均和最坏情况复杂度为O(N)
。 But the best-case complexity is O(1)
. 但是最好的情况是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
. 这是在第一次循环迭代中检测到的,并且与N
无关,花费恒定的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.