|
| 1 | +#!/usr/bin/env python |
| 2 | +# coding: utf-8 |
| 3 | + |
| 4 | +from __future__ import print_function |
| 5 | +import os |
| 6 | +import sys |
| 7 | +import glob |
| 8 | +import random |
| 9 | +import argparse |
| 10 | +import importlib |
| 11 | + |
| 12 | +from tabulate import tabulate |
| 13 | + |
| 14 | + |
| 15 | +def sort_algos(sample, sample_size, no_of_times, sample_range): |
| 16 | + pretty_print = lambda char, count: (print("{}".format(char*count))) |
| 17 | + current_dir = os.path.dirname(os.path.realpath(__file__)) |
| 18 | + |
| 19 | + sorting_algos = glob.glob("{}/*_sort.py".format(current_dir)) |
| 20 | + sorting_algos = [x.split('/')[-1][:-3] for x in sorting_algos] |
| 21 | + |
| 22 | + time_taken = [['Algorithm Name', 'Time Taken (Less Is Better!!)'], ] |
| 23 | + for algo in sorting_algos: |
| 24 | + module = importlib.import_module(algo) |
| 25 | + time_taken.append([algo.title().replace('_', ' '), |
| 26 | + "{0:.20f} sec".format(getattr(module, algo)(array=sample[:], |
| 27 | + repeat=no_of_times).time)]) |
| 28 | + pretty_print('|', 50) |
| 29 | + print( |
| 30 | + "Sorting Algorithms Ran!\nArray Details And Algorithms Summary As Follow") |
| 31 | + pretty_print('|', 50) |
| 32 | + pretty_print('-', 50) |
| 33 | + print("Length Of Array: {}".format(sample_size)) |
| 34 | + print("Range Of Numbers In Array: 0 to {}".format(sample_range-1)) |
| 35 | + print("Number Of Times Array Were Sorted: {}".format(no_of_times)) |
| 36 | + pretty_print('-', 50) |
| 37 | + print(tabulate(sorted(time_taken, key=lambda x: x[1], reverse=True), |
| 38 | + headers='firstrow', tablefmt="fancy_grid")) |
| 39 | + |
| 40 | + |
| 41 | +def run(): |
| 42 | + """ |
| 43 | + Main Function to execute sorting algorithms |
| 44 | + """ |
| 45 | + parser = argparse.ArgumentParser() |
| 46 | + parser.add_argument("-s", "--size", |
| 47 | + type=int, |
| 48 | + help="Size of array to be sorted", |
| 49 | + default=1000) |
| 50 | + parser.add_argument("-l", "--loop", |
| 51 | + type=int, |
| 52 | + help="Number of times array sorting should be repeated", |
| 53 | + default=1) |
| 54 | + parser.add_argument("-r", "--range", |
| 55 | + type=int, |
| 56 | + help="Max range of number that should be present in array", |
| 57 | + default=None) |
| 58 | + args = parser.parse_args() |
| 59 | + |
| 60 | + size = args.size |
| 61 | + repeat = args.loop |
| 62 | + max_range = args.range if args.range else size |
| 63 | + |
| 64 | + # Generate sample which will be sorted by all algorithms |
| 65 | + sample = [] |
| 66 | + try: |
| 67 | + sample = random.sample(range(max_range), size) |
| 68 | + except ValueError: |
| 69 | + print("Provided values range has to be greater than sample size") |
| 70 | + return None |
| 71 | + # Run all sorting algorithms |
| 72 | + sort_algos(sample, size, no_of_times=repeat, sample_range=max_range) |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + run() |
0 commit comments