java快速排序的时间复杂度,快速排序时间复杂度

I recently read about time complexity and I found out that Quick sort has an average time complexity of O(nlog(n)).

Question 1: What I do not understand is how is the log(n) present in the time complexity equation?

Question 2: Why do we always use the big O notation to find the time complexity of algorithms? Why don't we use other notations?

解决方案

How did the logn got into the complexity formula?

For each step, you invoke the algorithm recursively on the first and second half.

Thus - the total number of steps needed, is the number of times it will take to reach from n to 1 if you devide the problem by 2 each step.

So you are actually looking for a k such that:

n / 2 /2 / 2 / ... /2 = 1

^

(k times)

But, note that the equation is actually: n / 2^k = 1. Since 2^logn = n, we get k = logn. So the number of steps (iterations) the algorithm requires is O(logn), which will make the algorithm O(nlogn) - since each iteration is O(n).

Note: The complexity in here is not exact, quicksort in rare cases decays to O(n^2), it is depends on the pivot selection. The "devide the problem by 2 each step" is a simplification, but it does not change the average analyzis of the algorithm.

Why use big O notation?

It is simple and platform independent.

The exact number of op (and sometimes even comparisons) is platform dependent. (If instruction set A is richer then instruction set B, it will probably need more ops).

It is definetly not the only method used. For real life applications, the exact run time (in seconds) is very important factor and is often used.

So, in short - big O notation gives us easy to calculate - platform independent approximation on how will the algorithm behave asymptotically (at infinity), which can divide the "family" of algorithm into subsets of their complexity, and let us compare easily between them.

Also, other notations that are used are small o, theta and big/small omega.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值