I was working on an assignment in my Python class to sort 10 numbers but I wanted to be able to sort any set of numbers be it large or small. The assignment didn't really cover any sorting algorithms other than bubble sort so I started working and decided to just do something simple find the smallest number and remove it then put it in a temp list and then assign that list to the original to make it sorted. I was able to compress this down into the first sorting.
But I wanted to see if I could make it faster by also looking for the max and popping them both out in separate lists. But I was told python runs on a single thread and there were far more things to run than the first.
So why is the second sort slightly faster despite having more instructions than the first?
I ran this on python 3.8
import time
import random
rand_list = []
for i in range(0,10000):
n = random.randint(1,100000)
rand_list.append(n)
print('Random List Creation Complete')
list_to_sort1 = rand_list[:]
list_to_sort2 = rand_list[:]
''' Sort Smallest to Largest'''
start_time = time.time()
templist=[]
while 0 < len(list_to_sort1):
templist.append(list_to_sort1.pop(list_to_sort1.index(min(list_to_sort1))))
list_to_sort1 = templist
print('\nSorting Complete: My sort took', time.time() - start_time, "to run")
''' Sort Smallest to Largest'''
start_time = time.time()
min_half = []
max_half = []
max_pos = 0
min_pos = 0
while 0 < len(list_to_sort2):
max_pos = list_to_sort2.index(max(list_to_sort2))
min_pos = list_to_sort2.index(min(list_to_sort2))
if len(list_to_sort2) != 1:
if max_pos > min_pos:
max_half.append(list_to_sort2.pop(max_pos))
min_half.append(list_to_sort2.pop(min_pos))
else:
min_half.append(list_to_sort2.pop(min_pos))
max_half.append(list_to_sort2.pop(max_pos))
else:
min_half.append(list_to_sort2.pop(0))
max_half.reverse()
list_to_sort2 = min_half + max_half
print('\nSorting Complete: My sort 2 took', time.time() - start_time, "to run")
time.sleep(20)
why is the second sort slightly faster despite having more processes?
) that does not (quite) fit in here, as well as begging clarification: whatprocesses
are you referring to? \$\endgroup\$