I am trying my hand at algorithms for the first time and tried to create a sequential sorting algorithm. I have come up with the code below.
def SelectionSort(my_list):
prev_num = None
counter = 0
new_list = []
index_num = 0
new_list_counter = 0
for i in my_list:
if my_list.index(i) == 0:
prev_num = i
counter = 1
new_list.append(i)
else:
if i > prev_num:
prev_num = i
counter = 1
new_list.append(i)
else:
prev_num = i
for n in new_list:
if i >= n:
new_list_counter = 1
pass
else:
new_list.insert(new_list_counter, i)
index_num = new_list.index(i)
new_list_counter = 0
my_list.remove(i)
my_list.insert(index_num, i)
break
counter = 1
prev_num = i
return my_list
print(SelectionSort([1, 3, 4, 2, 6, 5]))
print(SelectionSort([3, 4, 2, 6]))
print(SelectionSort([3, 7, 4, 1]))
print(SelectionSort([3, 10, 2, 5]))
Whilst it seems to sort the first 3 lists just fine, when it comes to the last list it outputs [2, 3, 10, 5].
Can anyone possible lend a hand?
CodePudding user response:
I am sure the logic of your code could be improved and simplified. But with a small change it's working, at least with your 4 test cases.
My solution is to save "prev_num" with the higest existing number in the list using max(). And only save this value at the end of each loop.
def SelectionSort(my_list):
prev_num = None
counter = 0
new_list = []
index_num = 0
new_list_counter = 0
for i in my_list:
if my_list.index(i) == 0:
prev_num = i
counter = 1
new_list.append(i)
else:
if i > prev_num:
counter = 1
new_list.append(i)
else:
for n in new_list:
if i >= n:
new_list_counter = 1
else:
new_list.insert(new_list_counter, i)
index_num = new_list.index(i)
new_list_counter = 0
my_list.remove(i)
my_list.insert(index_num, i)
break
counter = 1
prev_num = i
prev_num = max(new_list) # <-- This is the key: Save at the end of each loop the highest existing number
return my_list
Improvements:
- The renaming of the "prev_num" variable to something like "highest_num".
- "elif" could be used instead of "else - if"
- Comment the code, not only for the reviewrs, it's useful for yourself too.