# Sorting Algorithm (from scratch) in Python

Updated (at the bottom)

I am attempting to write a Python program where I have to create a sorting algorithm without the assistance of the built-ins (like the sort() function). I used the def keyword to create the sorting_function() (the code bits in this paragraph will make more sense once you see my code) so all I have to do at the end is call the sorting_function(P.S. this is where the original_list needs to be passed as a parameter). My code (almost) works, but my concern is, how do I pass the original_list (or the user's input) as a parameter of the function? Instead of having my program edited by the user (where they have to go to the bottom of the program to insert the numbers of their list) for it to work? Also, silly me, the user is still going to edit the program, but it's easier and required to pass the original_list as a parameter of the sorting_algorithm function.

I also thought it would be helpful for you to know that I have no prior coding experience and that this is my first code in any programming language, so this may not be the most efficient code.

My code is as follows (my explanations might be too long, but I need to do this for clarity's sake. If any of my explanations are wrong/vague, please don't hesitate to correct me):

def sorting_algorithm(numbers):                                                         #this is the function in which the code will be written and upon completion, should be called on.
sorted_list = []                                                                    #the sorted_list variable is assigned to an empty list, which is where the sorted numbers will be stored.
index = 0                                                                           #the index starts from zero because, to effectively sort the numbers, the counting must start from the first number in the list.
comparison_number = 1                                                               #this is a comparison variable used for comparing the numbers in the list.

while numbers:
if numbers[index] == numbers[-1] and numbers[index] <= comparison_number:       #if the program reaches the last number in the list and it is smaller than the comparison_number (which is 1)
sorted_list.append(numbers.pop(index))                                      #then that number is put into the sorted_list's '[]'.
index = 0                                                                   #the index stays at zero for each if, elif and else statements as only one of these conditions can be true.
elif numbers[index] == numbers[-1]:                                             #if the program reaches the last number in the list,
index = 0                                                                   #then the position of the index should be returned to '0'.
comparison_number += 1                                                      #the comparison number will also go up by one because numbers (from the list) are being compared to the comparison number (which, again is 1)
elif numbers[index] <= comparison_number:                                       #if the number (under analysis) is less than or equals to comparison_number
sorted_list.append(numbers.pop(index))                                      #then that number can be placed into the sorted_list's '[]'.
index = 0                                                                   #the index is again returned to the first number in the list so it (the number) can be analyzed.
comparison_number += 1                                                      #the comparison_number goes up by one again because another number has been compared and added to the sorted_list's '[]'.
else:
index += 1                                                                  #if none of the above conditions apply to the number(s) in the list,
return sorted_list                                                                  #then the program will move onto the next number and the loop will restart! Also, I'm not entirely sure
#if the return sorted_list line is needed.

sorting_algorithm()                                                                     #this is how to call on the function, I believe.
original_list = [123, 85, 9587, 0, 453, 7, 63]                                          #this is where the user can/will input the numbers of their list.
print("The unsorted list: {}".format(original_list))                                    #I had to look at some examples of code to figure this out, I'm still not sure what '{}' is for...
original_list = sorting_algorithm(original_list)                                        ##but this will take the numbers of the list and go through the loop and put the numbers in ascending order.
print("And the sorted list: {}".format(original_list))                                  #at last, this line will print out the sorted list of numbers.


Note: I know that the names of my variables are really long (I used entire words to identify my vars), but it's easier for me to go back and know what those variables do. I'm very sorry if this is annoying to some of you, but since this is my first Python code, I believe it is essential for me to do this to achieve optimal clarity.

I hope my question isn't too vague, and if I can provide any further details, please let me know.

UPDATE:

After a couple of hours of trial and error I have (I think) finally figured out a better way to write this code. And the list is a parameter for my function! Thank you for all the help I got!!

def sorting_algorithm(list):
for index in range(1, len(list)):
current = list[index]
while index > 0 and list[index - 1] > current:
list[index] = list[index - 1]
index = index - 1
list[index] = current
return list

print("the sorted list is", (sorting_algorithm([45, 14, 1, 7, 98, 23, 102, 57])))


Could someone please let me know why I need the return list statement before printing the sorted list (I believe it's line 8)?

• There are numerous sorting algorithm e.g insertion sort, merge sort, quicksort. Why don't you implement them instead. Nov 30, 2020 at 17:59
• @theProgrammer I'm not sure how I would do that. Are these sorting algorithms you've provided above, built-in to Python? Or are you saying that I should use the method of one of these algorithms to optimize my code? I'm sorry if I'm completely missing your point here, but I brand new to this language, so please pardon my mistakes. Nov 30, 2020 at 18:07
• Python implements Tim-sort. You can reimplement insertion sort, it is fairly easy. Nov 30, 2020 at 18:14
• I believe theProgrammer is trying to direct you to tried-and-proven sorting algorithms, because writing your own sorting algorithm "from scratch" is likely to result in bad code (either incorrect, slow, or both). It has nothing to do with the language, and more with reinventing a particularly tricky (and very well studied) wheel. Nov 30, 2020 at 18:17
• @AryanParekh Thank you! I will make sure to check this channel out in detail when I have time. Nov 30, 2020 at 18:26