Skip to main content

A calculator to predict big-O of sorting functions

Project description

Table of Contents

Big-O Caculator

A big-O calculator to estimate time complexity of sorting functions.

inspired by : https://github.com/ismaelJimenez/cpp.leastsq

Installation

pip install big-O-calculator

What it does

You can test time complexity, calculate runtime, compare two sorting algorithms

Results may vary.

(n : [10, 100, 1_000, 10_000, 100_000])

Big-O calculator

Methods:
    def test(function, array="random", limit=True, prtResult=True):
        It will run only specified array test, returns Tuple[str, estimatedTime]

    def test_all(function):
        It will run all test cases, prints (best, average, worst cases), returns dict

    def runtime(function, array="random", size, epoch=1):
        It will simply returns execution time to sort length of size of test array, returns Tuple[float, List[Any]]

    def compare(function1, function2, array, size, epoch=3):
        It will compare two functions on {array} case, returns dict

Methods parameters

def test(**args):
    functionName [Callable]: a function to call.
    array [str]: "random", "big", "sorted", "reversed", "partial", "Ksorted", "string", "almost_equal", "equal", "hole".
    limit [bool] = True: To break before it takes "forever" to sort an array. (ex. selectionSort)
    prtResult [bool] = True: Whether to print result by itself

def test_all(**args):
    functionName [Callable]: a function to call.

def runtime(**args):
    functionName [Callable]: a function to call.
    array: "random", "big", "sorted", "partial", "reversed", "Ksorted" ,
        "hole", "equal", "almost_equal" or your custom array.
    size [int]: How big test array should be.
    epoch [int]: How many tests to run and calculte average.
    prtResult (bool): Whether to print the result by itself. (default = True)

def compare(**args):
    function1 [Callable]: a function to compare.
    function2 [Callable]: a function to compare.
    array [str]|[List]: "random", "big", "sorted", "partial", "reversed", "Ksorted", 
        "hole", "equal", "almost_equal", "all" or your custom array.
    size [int]: How big test array should be.

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().

Usage

from bigO import bigO
from bigO import algorithm

lib = 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 Example

from bigO import bigO
from random import randint

def quickSort(array):  # in-place | not-stable
    """
    Best : O(nlogn) Time | O(logn) Space
    Average : O(nlogn) Time | O(logn) Space
    Worst : O(n^2) Time | O(logn) Space
    """
    if len(array) <= 1:
        return array
    smaller, equal, larger = [], [], []
    pivot = array[randint(0, len(array) - 1)]
    for x in array:
        if x < pivot:
            smaller.append(x)
        elif x == pivot:
            equal.append(x)
        else:
            larger.append(x)
    return quickSort(smaller) + equal + quickSort(larger)


tester = bigO()
complexity, time = tester.test(quickSort, "random")
complexity, time = tester.test(quickSort, "sorted")
complexity, time = tester.test(quickSort, "reversed")
complexity, time = tester.test(quickSort, "partial")
complexity, time = tester.test(quickSort, "Ksorted")

''' Result
Running quickSort(random array)...
Completed quickSort(random array): O(nlog(n))
Time took: 0.35816s
Running quickSort(sorted array)...
Completed quickSort(sorted array): O(nlog(n))
Time took: 0.37821s
Running quickSort(reversed array)...
Completed quickSort(reversed array): O(nlog(n))
Time took: 0.38500s
Running quickSort(partial array)...
Completed quickSort(partial array): O(nlog(n))
Time took: 0.35820s
Running quickSort(Ksorted array)...
Completed quickSort(ksorted array): O(nlog(n))
Time took: 0.38140s
'''

Selection Sort Example

from bigO import bigO

def selectionSort(array):  # in-place, unstable
    '''
    Best : O(n^2) Time | O(1) Space
    Average : O(n^2) Time | O(1) Space
    Worst : O(n^2) Time | O(1) Space
    '''
    currentIdx = 0
    while currentIdx < len(array) - 1:
        smallestIdx = currentIdx
        for i in range(currentIdx + 1, len(array)):
            if array[smallestIdx] > array[i]:
                smallestIdx = i
        array[currentIdx], array[smallestIdx] = array[smallestIdx], array[currentIdx]
        currentIdx += 1
    return array


tester = bigO()
complexity, time = tester.test(selectionSort, "random")
complexity, time = tester.test(selectionSort, "sorted")
complexity, time = tester.test(selectionSort, "reversed")
complexity, time = tester.test(selectionSort, "partial")
complexity, time = tester.test(selectionSort, "Ksorted")

''' Result
Running selectionSort(random array)...
Completed selectionSort(random array): O(n^2)
Time took: 4.04027s
Running selectionSort(reversed array)...
Completed selectionSort(reversed array): O(n^2)
Time took: 4.04918s
Running selectionSort(sorted array)...
Completed selectionSort(sorted array): O(n^2)
Time took: 3.97238s
Running selectionSort(partial array)...
Completed selectionSort(partial array): O(n^2)
Time took: 4.02878s
Running selectionSort(Ksorted array)...
Completed selectionSort(ksorted array): O(n^2)
Time took: 4.05617s
'''

test_all(mySort) Example

We can test all "random", "sorted", "reversed", "partial", "Ksorted", "almost_equal" at once, and it shows, best, average and worst time complexity

from bigO import bigO

lib = bigO()

lib.test_all(bubbleSort)
lib.test_all(insertSort)

result = lib.test_all(selectionSort)

print(result)  # Dictionary


''' Result
Running bubbleSort(tests)
Best : O(n) Time
Average : O(n^2) Time
Worst : O(n^2) Time
Running insertSort(tests)
Best : O(n) Time
Average : O(n^2) Time
Worst : O(n^2) Time
Running selectionSort(tests)
Best : O(n^2) Time
Average : O(n^2) Time
Worst : 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) Example

array: "random", "big", "sorted", "partial", "reversed", "Ksorted", "hole", "equal", "almost_equal" or your custom array.

from bigO import bigO
from bigO import algorithm

lib = bigO()

timeTook, result = lib.runtime(algorithm.bubbleSort, "random", 5000)

custom = ["abc", "bbc", "ccd", "ef", "az"]

timeTook, result = lib.runtime(algorithm.bubbleSort, custom)

''' Result
Running 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) Example

array: "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)

'''Result
bubbleSort is 3.6% faster than insertSort on reversed case
Time Difference: 0.04513s
insertSortOptimized is 5959.3% faster than insertSort on reversed case
Time Difference: 1.25974s
quickSortHoare is 153.6% faster than quickSort on reversed case
Time Difference: 0.09869s
introSort is 206.6% faster than timSort on reversed case
Time Difference: 0.12597s
sorted is 12436.9% faster than introSort on reversed case
Time Difference: 0.06862s

Running bubbleSort(tests) vs insertSort(tests)
insertSort is 32.6% faster than bubbleSort on 6 of 8 cases
Time Difference: 0.11975s

{'bubbleSort': 0.4875642249999998, 'insertSort': 0.3678110916666666}
'''

@isSorted

If it sorts correctly, it shows: "mySort sorts correctly."

Otherwise, it shows like, "mySort doesn't sort correctly." "At N index: [...100, -72, 121...]

from bigO import bigO
from bigO import utils

@utils.isSorted
def bubbleSort(array):  # in-place | stable
    isSorted = False
    counter = 1  # not correct
    while not isSorted:
        isSorted = True
        for i in range(len(array) - 1 - counter):
            if array[i] > array[i + 1]:
                array[i], array[i + 1] = array[i + 1], array[i]
                isSorted = False

        counter += 1

    return array


if __name__ == "__main__":
    bubbleSort(bigO.genRandomArray(100))

''' Result
bubbleSort doesn't sort correctly.
At 99 index: [...99, -76]
'''

Array generators

from bigO import bigO

lib = bigO()

arr = lib.genRandomArray(100)
arr = lib.genRandomBigArray(100)
arr = lib.genRandomString(100)
arr = lib.genSortedArray(100)
arr = lib.genReversedArray(100)
arr = lib.genPartialArray(100)
arr = lib.genKsortedArray(100)
arr = lib.genAlmostEqualArray(100)
arr = lib.genEqualArray(100)
arr = lib.genHoleArray(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 list

Visit here to see codes

BinaryInsertSort, BubbleSort, CountSort, gnomeSort, heapSort, InsertSort, InsertSortOptimized, IntroSort, mergeSort, quickSort(random pivot), quickSortHoare(Hoare+Tail recur+InsertionSort), timSort(simplified)

Benchmarks

Visit here for more results

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

big-O calculator-0.0.9.8.2.tar.gz (21.5 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

big_O_calculator-0.0.9.8.2-py3.7.egg (175.0 kB view details)

Uploaded Egg

big_O_calculator-0.0.9.8.2-py3.7-win-amd64.egg (93.9 kB view details)

Uploaded Egg

big_O_calculator-0.0.9.8.2-py3-none-any.whl (21.0 kB view details)

Uploaded Python 3

File details

Details for the file big-O calculator-0.0.9.8.2.tar.gz.

File metadata

  • Download URL: big-O calculator-0.0.9.8.2.tar.gz
  • Upload date:
  • Size: 21.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0.post20200814 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.7.7

File hashes

Hashes for big-O calculator-0.0.9.8.2.tar.gz
Algorithm Hash digest
SHA256 bd3f4a78651f52760c8313ad0eaa814d9bfd7430e6bcc8379b9e6a4ecaa6bc36
MD5 789c6f24f272d206ee48d2eac1c773b1
BLAKE2b-256 533ae122231d15865d0485894785f2e499b816ed2fa8c638b30036068f243262

See more details on using hashes here.

File details

Details for the file big_O_calculator-0.0.9.8.2-py3.7.egg.

File metadata

  • Download URL: big_O_calculator-0.0.9.8.2-py3.7.egg
  • Upload date:
  • Size: 175.0 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2.post20201201 requests-toolbelt/0.9.1 tqdm/4.54.0 CPython/3.7.7

File hashes

Hashes for big_O_calculator-0.0.9.8.2-py3.7.egg
Algorithm Hash digest
SHA256 8421322883614e5dbce8c7b9db04129a55e5cda16675d77e3567cf8959991385
MD5 c8efce8ad286fe1492befc83daa1fa69
BLAKE2b-256 3cf1b775c6bdac68383bd54b57e4130080c1f5c712b32fcecac4e45b11f1cfcb

See more details on using hashes here.

File details

Details for the file big_O_calculator-0.0.9.8.2-py3.7-win-amd64.egg.

File metadata

  • Download URL: big_O_calculator-0.0.9.8.2-py3.7-win-amd64.egg
  • Upload date:
  • Size: 93.9 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2.post20201201 requests-toolbelt/0.9.1 tqdm/4.54.0 CPython/3.7.7

File hashes

Hashes for big_O_calculator-0.0.9.8.2-py3.7-win-amd64.egg
Algorithm Hash digest
SHA256 3c09b42bc06ebee78dd448caab93149344482c2fecb79e31951274210c2d94c1
MD5 e0b6509a95dc08315ee7a1c5bbee1cc3
BLAKE2b-256 7afd18c626c4c006ae97cbdef54b2d634d979f3fc8b12fdab11239515951a177

See more details on using hashes here.

File details

Details for the file big_O_calculator-0.0.9.8.2-py3-none-any.whl.

File metadata

  • Download URL: big_O_calculator-0.0.9.8.2-py3-none-any.whl
  • Upload date:
  • Size: 21.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0.post20200814 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.7.7

File hashes

Hashes for big_O_calculator-0.0.9.8.2-py3-none-any.whl
Algorithm Hash digest
SHA256 97682b7479cf7179e3fdd12b83181343cfe4b5bd48e1f34de65e8fb73b0f9b35
MD5 32c85f6cd34f4d7efda5309bfe045478
BLAKE2b-256 f3e18abcd5ba0b2c249d25c1f16cc8aa9838c993061ce322b0ac5ed42251a5d0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page