简体   繁体   English

最佳情况时间复杂度检查数组是否未排序

[英]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.

相关问题 在未排序数组中插入的最佳情况和最坏情况时间复杂度 - best case and worst case time complexity for insertion in unsorted array 二阶搜索未排序数组的时间复杂度 - Time complexity of binary search for an unsorted array 算法 - 未排序数组中删除的时间复杂度 - Algorithm - the time complexity of deletion in a unsorted array 以最佳时间复杂度 [Java] 在未排序的整数数组中找到两个相同数字之间的最大差异 - Find the Maximum difference between two Same Numbers in an unsorted array of integers in best Time Complexity [Java] 为什么对未排序数组O(n)进行线性搜索的最佳和最差情况? - Why is the best and worst case of linear search of an unsorted array O(n)? 在插入、删除的最佳情况下,排序数组、排序链表和二叉搜索树的时间复杂度是多少 - What's the time complexity for Sorted Array, Sorted Linked List and Binary Search Tree in Best Case for Insertion, Deletion 查找阵列中最小元素索引的时间复杂度分析 - 最差,平均和最佳情况 - Time complexity analysis in finding index of smallest element in an array-worst,average and best case 在对数时间内以未排序的数组搜索 - searching in an unsorted array in logrithmic time 在一个密切排序的元素数组中搜索元素的最坏情况时间复杂度? - Worst case time complexity to search an element in a closely sorted array of elements? 是否可以使用 Floyd 的龟兔算法在 O(n) 时间、O(1) 空间复杂度内从未排序的数组中删除重复项? - Is it possible to remove duplicates from an unsorted array in O(n) time, O(1) space complexity, using the Floyd's tortoise and hare algorithm?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM