I made a simple Python program which takes a list of unique numbers and orders them from smallest to greatest. The algorithm (which is actually quite similar to bubble sort) works like this:
- Take the first number
- If it is larger than the next number, switch them
- If it is smaller than the next number, do nothing
- Continue to next number until the algorithm has done this to everything in the list
- Check if the list is in the correct order
- If not, repeat the process
- If it is, print out the list in order and time taken in seconds
import random
import time
import sys
sys.setrecursionlimit(10000)
value_list = []
# Create values
len_of_list = random.randint(8500, 10000)
for number in range(0, len_of_list):
value_list.append(number)
random.shuffle(value_list)
def timeit(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print "The function {.__name__} took {:.15f} seconds to finish.".format(func, time.time() - start)
return result
return wrapper
def custom_sort():
for index in range(0, len_of_list):
if (index + 1) == len_of_list:
if not check_results():
custom_sort()
elif check_results():
print value_list
else:
if value_list[index] > value_list[index + 1]:
smaller_val = value_list[index + 1]
value_list[index + 1] = value_list[index]
value_list[index] = smaller_val
elif value_list[index] < value_list[index + 1]:
continue
def check_results():
for index in range(0, len_of_list):
if (index + 1) == len_of_list:
return True
else:
if value_list[index] < value_list[index + 1]:
continue
elif value_list[index] > value_list[index + 1]:
return False
@timeit
def run():
custom_sort()
run()
I have made a function called run()
specifically so that @timeit
only prints out one line stating how long it took to finish. custom_sort()
sorts the numbers in the list for the first four bullets. check_results()
checks if the list is in order like in the last three bullets. sys.setrecursionlimit(10000)
is used so that I don't get a recursion error since the list can hold up to 10000 numbers.
Example output (due to reports of crashing, I will replace most of the values with ... , I hope you understand what the result should be):
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, ... 9669, 9670, 9671, 9672, 9673, 9674, 9675, 9676, 9677, 9678, 9679, 9680] The function run took 24.037000179290771 seconds to finish.
Is there a way to shorten my code and make my algorithm faster? The slowest it has been is about 36 seconds to sort the maximum amount of numbers (10000).