帮助验证Big O.

时间:2011-05-31 03:40:53

标签: sorting big-o

嘿所以我试图验证一些排序算法。

  • 插入排序

  • 归并

  • 使用“三个中位数”分区和截止值为10的Quicksort(使用小数组部分的插入排序)

分析:
插入排序的最坏情况运行时间被讨论为O(n 2 ),实际运行时间为O(n),用于排序输入(只要内部循环被正确编码)。对于所有输入,Mergesort被讨论为O(n log n)。对于所有输入,使用“三个中值”分区和合理截止的Quicksort被讨论为O(n Log(n)),但在实践中比Mergesort更快。您的计时是否验证了这些计算?

注意N = Max / 2,2N = MAX

运行程序后,我找到了

The diff for insertion sorted with sorted max/2 is 0.000307083129882812
The diff for insertion sorted with sorted max is 0.000623941421508789
The diff for insertion reverse with sorted max/2 is 0.000306129455566406
The diff for insertion reverse with sorted max is 0.000745058059692383
The diff for insertion random with sorted max/2 is 2.39158606529236
The diff for insertion random with sorted max is 9.72073698043823
The diff for merge sort with sorted max/2 is 0.00736188888549805
The diff for merge sort with sorted max is 0.0154471397399902
The diff for merge reverse with sorted max/2 is 0.00730609893798828
The diff for merge reverse with sorted max is 0.0154309272766113
The diff for merge random with sorted max/2 is 0.0109999179840088
The diff for merge random with sorted max is 0.0232758522033691
The diff for quick sorted with sorted max/2 is 3.10367894172668
The diff for quick sorted with sorted max is 12.5512340068817
The diff for quick reverse with sorted max/2 is 3.09689497947693
The diff for quick reverse with sorted max is 12.5547797679901
The diff for quick random with sorted max/2 is 0.0112619400024414
The diff for quick random with sorted max is 0.0221798419952393

我知道插入排序正常工作,因为对于随机,我做了9.72073698043823 / 2.39158606529236~ = 4 = 2 2 = O(n 2

但我不知道如何验证其他的是否是O(n Log(n))。请帮忙

1 个答案:

答案 0 :(得分:2)

让我提醒你,f(n)= O(n)意味着当n增长很大时f(n)/ n =>恒定

什么没说:

  • 那个常数可能很大
  • 对于小值,它意味着某些东西:例如: 10 ^ 9 / n + n是O(n)但是对于n = 1,它是10 ^ 9 + 1; - )
  • O(某事物)不是参数杀手,数据的拓扑结构可能会在某种程度上影响算法(例如:“几乎”排序的数据,冒泡排序表现良好)

如果你想得出结论,使用与你的应用相关的大样本运行测试,不要过早得出结论(注意现代CPU可能会欺骗你使用缓存,流水线和多核如果你使用它(你能做什么)分选)