Last active
July 8, 2020 05:14
-
-
Save sonaalPradeep/8b2d4f24e854fca011e8778461f8a5fc to your computer and use it in GitHub Desktop.
Bogosort to retrieve running times and plot
This file contains 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
import argparse | |
import random | |
import time | |
import pandas as pd | |
import seaborn as sns | |
sns.set(style = "whitegrid") | |
def generate_initial(num_of_elements): | |
''' | |
Generate a shuffled array of a given length | |
''' | |
array = list(range(num_of_elements)) | |
random.shuffle(array) | |
return array | |
def check_sorted(array): | |
''' | |
Check if the array is sorted (in ascending order) | |
''' | |
for ind in range(len(array) - 1): | |
if array[ind] > array[ind + 1]: | |
return False | |
return True | |
def bogo_sort(array): | |
''' | |
Bogosort the array. Shuffle the array randomly and | |
return the sorted array as well as the time | |
taken by the algorithm | |
''' | |
start_time = time.time() | |
while not check_sorted(array): | |
''' | |
random.shuffle(array) cannot be used since the function shuffles inplace. | |
If used, the first iteration for a specific size will show the true time, | |
but all the other iterations would return the time immediately since the array is already arranged | |
''' | |
array = random.sample(array, len(array)) | |
return array, time.time() - start_time | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description = "Program to analyse time taken by bogosort") | |
parser.add_argument("--version", action = "version", version = "v1.2") | |
parser.add_argument("--max_size", type = int, default = 10, help = "The maximum size of the arrays to be timed") | |
parser.add_argument("--min_size", type = int, default = 2, help = "The minimum size of the arrays to be timed") | |
parser.add_argument("--samples", type = int, default = 5, help = "Number of samples to take per size") | |
args = parser.parse_args() | |
max_size_of_array = args.max_size | |
min_size_of_array = max(1, args.min_size) | |
number_of_samples = max(1, args.samples) | |
size_list = list(range(min_size_of_array, max_size_of_array + 1)) | |
times_df = pd.DataFrame() | |
for size in size_list: | |
initialised_array = generate_initial(size) | |
times = [bogo_sort(initialised_array)[1] for _ in range(number_of_samples)] | |
times_df[size] = times | |
times_df.to_csv("bogoSort_times.csv") | |
sns_plot = sns.pointplot(data = times_df, join = False) | |
sns_plot.set(xlabel = "Size of Array", ylabel = "Time (seconds)", title = "Time vs. Size Graph") | |
sns_fig = sns_plot.get_figure() | |
sns_fig.set_size_inches(18.5, 10.5) | |
sns_fig.savefig("time_plots.png") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment