Created
August 9, 2018 19:46
-
-
Save ripiuk/c2fbe6987f586f7be142231dbe710209 to your computer and use it in GitHub Desktop.
Comparison. Selection sort vs Quick sort. Big O.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import clock | |
from random import randint | |
from collections import namedtuple | |
MASS = [randint(0, 9456) for i in range(10000)] | |
def find_the_smallest_index(mass: list) -> int: | |
the_smallest_index = 0 | |
for index in range(len(mass)): | |
if mass[index] < mass[the_smallest_index]: | |
the_smallest_index = index | |
return the_smallest_index | |
def selection_sort(mass: list) -> list: | |
mass = mass.copy() | |
sorted_mass = list() | |
while mass: | |
sorted_mass.append(mass.pop(find_the_smallest_index(mass))) | |
return sorted_mass | |
def quick_sort(mass: list) -> list: | |
if len(mass) < 2: | |
return mass | |
else: | |
kernel = mass[0] | |
less = [el for el in mass[1:] if el <= kernel] | |
greater = [el for el in mass[1:] if el > kernel] | |
return quick_sort(less) + [kernel] + quick_sort(greater) | |
def print_results(functions: list, *args) -> None: | |
Output = namedtuple('Output', ['func_name', 'result', 'time']) | |
title = Output('Function', 'Result', 'Time') | |
results = [title] | |
for func in functions: | |
search_start = clock() | |
res = func(*args) | |
search_time = clock() - search_start | |
results.append(Output(func.__name__, res, search_time)) | |
func_name_column_size = max([len(str(result.func_name)) for result in results]) | |
res_column_size = max([len(str(result.result)) for result in results]) | |
time_column_size = max([len(str(result.time)) for result in results]) | |
for _name, _result, _time in results: | |
print(f'{_name:<{func_name_column_size}} | {str(_result):<{res_column_size}} | ' | |
f'{_time:<{time_column_size}}') | |
if __name__ == "__main__": | |
print_results([selection_sort, quick_sort], MASS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment