Package: big-O-calculator
Table of ContentsMethodsUsageQuickSort exampletest_all() exmapleruntime() exmaplecompare() exmaple@isSorted decoratorArray generatorsTest arrays sampleBig-O CaculatorA big-O calculator to estimate time complexity of sorting functions.inspired by :https://github.com/ismaelJimenez/cpp.leastsqInstallationpipinstallbig-O-calculatorWhat it doesYou can test time complexity, calculate runtime, compare two sorting algorithmsResults may vary.(n : [10, 100, 1_000, 10_000, 100_000])Big-OcalculatorMethods:deftest(function,array="random",limit=True,prtResult=True):Itwillrunonlyspecifiedarraytest,returnsTuple[str,estimatedTime]deftest_all(function):Itwillrunalltestcases,prints(best,average,worstcases),returnsdictdefruntime(function,array="random",size,epoch=1):Itwillsimplyreturnsexecutiontimetosortlengthofsizeoftestarray,returnsTuple[float,List[Any]]defcompare(function1,function2,array,size,epoch=3):Itwillcomparetwofunctionson{array}case,returnsdictMethods parametersdeftest(**args):function[Callable]:afunctiontocall.array[str]:"random","big","sorted","reversed","partial","Ksorted","string","almost_equal","equal","hole".limit[bool]=True:Tobreakbeforeittakes"forever"tosortanarray.(ex.selectionSort)prtResult[bool]=True:Whethertoprintresultbyitselfdeftest_all(**args):function[Callable]:afunctiontocall.defruntime(**args):function[Callable]:afunctiontocall.array:"random","big","sorted","partial","reversed","Ksorted","hole","equal","almost_equal"oryourcustomarray.size[int]:Howbigtestarrayshouldbe.epoch[int]:Howmanyteststorunandcalculteaverage.prtResult(bool):Whethertoprinttheresultbyitself.(default=True)defcompare(**args):function1[Callable]:afunctiontocompare.function2[Callable]:afunctiontocompare.array[str]|[List]:"random","big","sorted","partial","reversed","Ksorted","hole","equal","almost_equal","all"oryourcustomarray.size[int]:Howbigtestarrayshouldbe.Info:
To see the result of function, return the array.These methods will also check if the function sorts correctly.

"K" in Ksorted uses testSize.bit_length().UsagefrombigOimportBigOfrombigOimportalgorithmlib=BigO()lib.test(bubbleSort,"random")lib.test_all(bubbleSort)lib.runtime(bubbleSort,"random",5000)lib.runtime(algorithm.insertSort,"reversed",32)lib.compare(algorithm.insertSort,algorithm.bubbleSort,"all",5000)Quick Sort ExamplefrombigOimportBigOfromrandomimportrandintdefquickSort(array):# in-place | not-stable"""Best : O(nlogn) Time | O(logn) SpaceAverage : O(nlogn) Time | O(logn) SpaceWorst : O(n^2) Time | O(logn) Space"""iflen(array)<=1:returnarraysmaller,equal,larger=[],[],[]pivot=array[randint(0,len(array)-1)]forxinarray:ifx<pivot:smaller.append(x)elifx==pivot:equal.append(x)else:larger.append(x)returnquickSort(smaller)+equal+quickSort(larger)lib=BigO()complexity=lib.test(quickSort,"random")complexity=lib.test(quickSort,"sorted")complexity=lib.test(quickSort,"reversed")complexity=lib.test(quickSort,"partial")complexity=lib.test(quickSort,"Ksorted")''' ResultRunning quickSort(random array)...Completed quickSort(random array): O(nlog(n))Running quickSort(sorted array)...Completed quickSort(sorted array): O(nlog(n))Running quickSort(reversed array)...Completed quickSort(reversed array): O(nlog(n))Running quickSort(partial array)...Completed quickSort(partial array): O(nlog(n))Running quickSort(Ksorted array)...Completed quickSort(ksorted array): O(nlog(n))'''Selection Sort ExamplefrombigOimportBigOdefselectionSort(array):# in-place, unstable'''Best : O(n^2) Time | O(1) SpaceAverage : O(n^2) Time | O(1) SpaceWorst : O(n^2) Time | O(1) Space'''currentIdx=0whilecurrentIdx<len(array)-1:smallestIdx=currentIdxforiinrange(currentIdx+1,len(array)):ifarray[smallestIdx]>array[i]:smallestIdx=iarray[currentIdx],array[smallestIdx]=array[smallestIdx],array[currentIdx]currentIdx+=1returnarraylib=BigO()complexity=lib.test(selectionSort,"random")complexity=lib.test(selectionSort,"sorted")complexity=lib.test(selectionSort,"reversed")complexity=lib.test(selectionSort,"partial")complexity=lib.test(selectionSort,"Ksorted")''' ResultRunning selectionSort(random array)...Completed selectionSort(random array): O(n^2)Running selectionSort(sorted array)...Completed selectionSort(sorted array): O(n^2)Running selectionSort(reversed array)...Completed selectionSort(reversed array): O(n^2)Running selectionSort(partial array)...Completed selectionSort(partial array): O(n^2)Running selectionSort(Ksorted array)...Completed selectionSort(ksorted array): O(n^2)'''test_all(mySort) ExampleWe can test all "random", "sorted", "reversed", "partial", "Ksorted", "almost_equal" at once,
and it shows, best, average and worst time complexityfrombigOimportBigOlib=BigO()lib.test_all(bubbleSort)lib.test_all(insertSort)result=lib.test_all(selectionSort)print(result)# Dictionary''' ResultRunning bubbleSort(tests)Best : O(n) TimeAverage : O(n^2) TimeWorst : O(n^2) TimeRunning insertSort(tests)Best : O(n) TimeAverage : O(n^2) TimeWorst : O(n^2) TimeRunning selectionSort(tests)Best : O(n^2) TimeAverage : O(n^2) TimeWorst : O(n^2) Time{'random': 'O(n^2)', 'sorted': 'O(n^2)', 'reversed': 'O(n^2)', 'partial': 'O(n^2)', 'Ksorted': 'O(n^2)'}'''runtime(mySort) Examplearray: "random", "big", "sorted", "partial", "reversed", "Ksorted",
"hole", "equal", "almost_equal" or your custom array.frombigOimportBigOfrombigOimportalgorithmlib=BigO()timeTook,result=lib.runtime(algorithm.bubbleSort,"random",5000)custom=["abc","bbc","ccd","ef","az"]timeTook,result=lib.runtime(algorithm.bubbleSort,custom)''' ResultRunning bubbleSort(len 5000 random array)Took 2.61346s to sort bubbleSort(random)Running bubbleSort(len 5 custom array)Took 0.00001s to sort bubbleSort(custom)'''compare(mySort, thisSort) Examplearray: "random", "big", "sorted", "partial", "reversed", "Ksorted",
"hole", "equal", "almost_equal", "all" or your custom array.lib=BigO()result=lib.compare(algorithm.bubbleSort,algorithm.insertSort,"reversed",5000)result=lib.compare(algorithm.insertSort,algorithm.insertSortOptimized,"reversed",5000)result=lib.compare(algorithm.quickSort,algorithm.quickSortHoare,"reversed",50000)result=lib.compare(algorithm.timSort,algorithm.introSort,"reversed",50000)result=lib.compare(sorted,algorithm.introSort,"reversed",50000)result=lib.compare(algorithm.bubbleSort,algorithm.insertSort,"all",5000)print(result)'''ResultbubbleSort is 3.6% faster than insertSort on reversed caseTime Difference: 0.04513sinsertSortOptimized is 5959.3% faster than insertSort on reversed caseTime Difference: 1.25974squickSortHoare is 153.6% faster than quickSort on reversed caseTime Difference: 0.09869sintroSort is 206.6% faster than timSort on reversed caseTime Difference: 0.12597ssorted is 12436.9% faster than introSort on reversed caseTime Difference: 0.06862sRunning bubbleSort(tests) vs insertSort(tests)insertSort is 32.6% faster than bubbleSort on 6 of 8 casesTime Difference: 0.11975s{'bubbleSort': 0.4875642249999998, 'insertSort': 0.3678110916666666}'''@isSortedIf it sorts correctly, it shows: "mySort sorts correctly."Otherwise, it shows like,
"mySort doesn't sort correctly."
"At N index: [...100, -72, 121...]frombigOimportBigOfrombigOimportutils@utils.is_sorteddefbubbleSort(array):# in-place | stableisSorted=Falsecounter=1# not correctwhilenotisSorted:isSorted=Trueforiinrange(len(array)-1-counter):ifarray[i]>array[i+1]:array[i],array[i+1]=array[i+1],array[i]isSorted=Falsecounter+=1returnarrayif__name__=="__main__":bubbleSort(BigO.gen_random_ints(100))''' ResultbubbleSort doesn't sort correctly.At 99 index: [...99, -76]'''Array generatorsfrombigOimportBigOlib=BigO()arr=lib.gen_random_ints(100)arr=lib.gen_random_big_ints(100)arr=lib.gen_random_strings(100)arr=lib.gen_sorted_ints(100)arr=lib.gen_reversed_ints(100)arr=lib.gen_partial_ints(100)arr=lib.gen_ksorted_ints(100)arr=lib.gen_equal_ints(100)arr=lib.gen_almost_equal_ints(100)arr=lib.gen_hole_ints(100)Test arrays sample (size = 20)Results vary.random=[15,15,-11,-16,-19,-16,-14,14,19,2,18,-10,5,-17,-4,-2,9,12,8,12]randomBig=[-996061023766482,347955820115093,...]string=['rwe55pi8hkwpjv5rhhoo','5ecvybo5xi8p25wanh3t',...]sorted=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]reversed=[19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0]partial=[-18,14,7,-11,17,5,6,7,8,9,14,9,-13,0,14,-17,-18,-9,-16,14]Ksorted=[-4,-5,-6,-7,-8,-9,-10,-3,-2,-1,0,1,2,3,4,5,6,7,9,8]almost_equal=[19,19,19,20,20,19,20,20,21,19,20,21,21,19,19,21,20,19,21,19]equal=[16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16]hole=[-7,-7,-7,-7,-7,-7,-9999,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7]Built-in algorithms listVisithereto see codesBinaryInsertSort, BubbleSort, CountSort, gnomeSort, heapSort,
InsertSort, InsertSortOptimized, IntroSort,
mergeSort, quickSort(random pivot), quickSortHoare(Hoare+Tail recur+InsertionSort), timSort(simplified)BenchmarksVisitherefor more results