为什么会冒泡排序为O(n ^ 2)?

编程入门 行业动态 更新时间:2024-10-21 03:18:05
本文介绍了为什么会冒泡排序为O(n ^ 2)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 int currentMinIndex = 0; for (int front = 0; front < intArray.length; front++) { currentMinIndex = front; for (int i = front; i < intArray.length; i++) { if (intArray[i] < intArray[currentMinIndex]) { currentMinIndex = i; } } int tmp = intArray[front]; intArray[front] = intArray[currentMinIndex]; intArray[currentMinIndex] = tmp; }

的内循环迭代:N +(N-1)+(N-2)+(N-3)+ ... + 1次

The inner loop is iterating: n + (n-1) + (n-2) + (n-3) + ... + 1 times.

外循环迭代:n次

所以,你得到N *(数字1到n的总和)

So you get n * (the sum of the numbers 1 to n)

这不就是N *(N *(N + 1)/ 2)= N *((N ^ 2)+ N / 2)

Isn't that n * ( n*(n+1)/2 ) = n * ( (n^2) + n/2 )

这将是(N ^ 3)+(N ^ 2)/ 2 = O(N ^ 3)?

Which would be (n^3) + (n^2)/2 = O(n^3) ?

我肯定我这样做是错误的。为什么不是为O(n ^ 3)?

I am positive I am doing this wrong. Why isn't O(n^3)?

推荐答案

您是正确的,外层循环迭代n次,内部循环迭代n次为好,但你是重复计算的工作。如果算上向上和总结整个顶层循环的每次迭代完成你得到的第一迭代确实Ñ工作,第二n的工作完成的总功 - 1,第三个N - 2等,由于第i个顶层循环迭代有内环做 N - 我工作

You are correct that the outer loop iterates n times and the inner loop iterates n times as well, but you are double-counting the work. If you count up the total work done by summing the work done across each iteration of the top-level loop you get that the first iteration does n work, the second n - 1, the third n - 2, etc., since the ith iteration of the top-level loop has the inner loop doing n - i work.

另外,你可以指望由工作由内部循环时间做的次数循环运行的总数量乘以所做的工作。内环确实为O(n)在每个迭代的工作,和外循环运行为O(n)的迭代,所以总的工作是O(n 2 )。

Alternatively, you could count up the work done by multiplying the amount of work done by the inner loop times the total number of times that loop runs. The inner loop does O(n) work on each iteration, and the outer loop runs for O(n) iterations, so the total work is O(n2).

您正试图通过这两种策略相结合犯错误。这是真的,外环并在第一时间n的工作,则n - 1,则n - 2,等,但是,不进行n乘以这项工作,以获得总。这将算在每次迭代n次。相反,你可以归纳在一起。

You're making an error by trying to combine these two strategies. It's true that the outer loop does n work the first time, then n - 1, then n - 2, etc. However, you don't multiply this work by n to to get the total. That would count each iteration n times. Instead, you can just sum them together.

希望这有助于!

更多推荐

为什么会冒泡排序为O(n ^ 2)?

本文发布于:2023-11-29 16:30:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!