简体   繁体   English

O(n) 和 O(n logn) 之间的比较

[英]Comparision between O(n) and O(n logn)

Which is best algo for a normal search in array where array length is not known在数组长度未知的数组中,哪个是正常搜索的最佳算法

O(n) (A simple for loop) O(n)(一个简单的 for 循环)

Or或者

O(n log n) (sorted(array)) in python O(n log n) (sorted(array)) in python

Correct me if the Time Complexity is wrong and also add any useful additional information.如果时间复杂度错误,请纠正我,并添加任何有用的附加信息。

Thanks in advance提前致谢

It depends on how often you'll be doing the search.这取决于您进行搜索的频率。

  • Looking for a specific item in an unsorted list takes O(n) time.在未排序列表中查找特定项目需要 O(n) 时间。
  • Looking for a specific item in a sorted list takes O(lg n) time.排序列表中查找特定项目需要 O(lg n) 时间。
  • Turning an unsorted list into a sorted list takes O(n lg n) time.将未排序列表转换为排序列表需要 O(n lg n) 时间。

Doing a single linear search in an unsorted list is faster than sorting the list in order to do a single binary search.在未排序的列表中进行单个线性搜索比对列表进行排序以进行单个二进制搜索要快。

But doing multiple linear searches in an unsorted list can be much slower than sorting the list once and doing multiple binary searches in the sorted list.但是在未排序列表中进行多次线性搜索可能比对列表进行一次排序并在排序列表中进行多次二进制搜索慢得多。


When will it be faster overall to spend the time sorting the list to speed up future searches compared to just biting the bullet and doing linear searches?与硬着头皮进行线性搜索相比,花时间对列表进行排序以加快未来搜索的总体速度何时会更快? You can only answer that by carefully consider the size of the list, and trying to anticipate your likely workload.您只能通过仔细考虑列表的大小并尝试预测您可能的工作量来回答这个问题。

Consider k searches.考虑k个搜索。 Sorting comes out on top if (using some very handwavy math) O(n lg n) + kO(lg n) is less than kO(n).如果(使用一些非常手摇的数学)O(n lg n)+ kO(lg n)小于kO(n),则排序排在首位。 That's true somewhere around the time k starts to exceed lg n .这在k开始超过lg n的某个时间是正确的。 Given how slowly lg n grows, it typically does not take long for the initial investment in sorting to pay off.考虑到lg n的增长速度有多慢,最初的排序投资通常很快就会得到回报。

yes you are correct: for a single for loop of n integers the time complexity is O(n)是的,你是对的:对于 n 个整数的单个 for 循环,时间复杂度为 O(n)

for(int i=0 ;i<n ; i++0)

if we have two for loops one inside another the it was o(n^2) best example is bubble sort如果我们有两个 for 循环,一个在另一个里面,那就是 o(n^2) 最好的例子是冒泡排序

for(int i=0 ;i<n ; i++){
for (int j=0;j<n;j++){
                     .....................}}

if i value decreases into half for every iteration then the complexity will be in terms of log best example is mergsort,binary search如果每次迭代 i 的值减半,那么复杂度将以 log 为单位 最好的例子是 mergsort,二分搜索

for(int i=0 ;i<n ; i=i/2){}

searching for a item in a sorted list takes O(log n) time it was the best method.在排序列表中搜索项目需要O(log n)时间,这是最好的方法。 best application is binary search最好的应用是binary search

converting an unsorted list into a sorted list takes O(n*logn) time ie merge sort,heap sort.将未排序列表转换为排序列表需要O(n*logn)时间,即merge sort,heap sort.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM