2
\$\begingroup\$

I'm taking a Python course and the current assignment is to create an algorithm that sorts numbers in ascending order (without using built-in sorting functions). I've had no programming experience before taking this course, so this might be a bit rough.

I got my script to successfully sort the numbers by figuring out the smallest number in the list each time through and moving it to a new list. This is obviously not very efficient since it has to loop dozens of times just for a short list, but I'm happy I finally got something to work! (Also, I think I need another elif to account for lists with repeat numbers.)

How can I clean it up? Is it more complex than it needs to be? I know there are far more efficient ways to sort, but I don't want to just copy someone else's established algorithm. I'd like to keep as much of this code in tact as possible while nipping and tucking.

def sortFunc(*arg):

    numList = list(arg)                     # Converts arguments into a list
    print('Before sorting: ',numList)       # Prints that list before sorting happens
    numSort = []                            # Creates an empty list to put sorted numbers into
    i = 0                                   # This is the index
    a = 1                                   # 'a' is the comparison number (this is the magic sauce)

    while numList:                          # As long as numList has numbers in it, loop the following

        if numList[i] == numList[-1] and\
           numList[i] <= a:                 # If we're at the final index AND that last number is smaller than 'a'
            basket = numList.pop(i)         # then place that number in a basket
            numSort.append(basket)          # and dump the basket into the new list (numSort)
            i = 0

        elif numList[i] == numList[-1]:     # Otherwise, if we reach the last position in numList 
            i = 0                           # reset the index back to the first position
            a = a+1                         # and make the comparison number a little bigger

        elif numList[i] <= a:               # If we're anywhere else in the list and that number is smaller than 'a'
            basket = numList.pop(i)         # then pop that number into the basket
            numSort.append(basket)          # and dump it unceremoniously into the new list (numSort)
            i = 0                           # Then reset the index back to the first position
            a = a+1                         # and make the comparison number a little bigger

        else:                               # If none of those things happen
            i = i+1                         # then move on to the next number in the list

    print('After sorting: ',numSort)        # Once the while loop is up, print the result!


sortFunc(67, 45, 2, 13, 1, 998)
\$\endgroup\$
1
\$\begingroup\$

Not bad for a first attempt!

I have made some modifications, none of them are towards speed/effency.

  1. Follow PEP8 style guide for naming your variables and functions. It just the way to write python.
  2. Don't print in functions, print outside functions
  3. Don't accept *args to just make it a list. Accept a variable you expect to be a list then just act on it as if it were a list.
  4. Throw away variables are handy if you plan on using them more than once. But if it is just to append it to another list just nest the operation.

    basket = numList.pop(i)
    numSort.append(basket)
    

    becomes

    numSort.append(numList.pop(i))
    
  5. Use i += 1 instead of i = i + 1, it's just cleaner.
  6. You're comments are a bit over verbose. I didn't update any comments so they may be wrong in the modified code below.

Here is the modified code.

def sort_func(values):
    num_sort = []  # Creates an empty list to put sorted numbers into
    i = 0  # This is the index
    a = 1  # 'a' is the comparison number (this is the magic sauce)

    while values:  # As long as numList has numbers in it, loop the following
        if values[i] == values[-1] and values[i] <= a:  # If we're at the final index AND that last number is smaller than 'a'
            num_sort.append(values.pop(i))
            i = 0
        elif values[i] == values[-1]:  # Otherwise, if we reach the last position in numList
            i = 0  # reset the index back to the first position
            a += 1  # and make the comparison number a little bigger
        elif values[i] <= a:  # If we're anywhere else in the list and that number is smaller than 'a'
            num_sort.append(values.pop(i))
            i = 0  # Then reset the index back to the first position
            a += 1  # and make the comparison number a little bigger
        else:  # If none of those things happen
            i += 1  # then move on to the next number in the list
    return num_sort

my_list = [67, 45, 2, 13,  13, 1, 998]
print("Before sorting {}".format(my_list))
my_list = sort_func(my_list)
print("After sorting {}".format(my_list))
\$\endgroup\$
1
\$\begingroup\$

Congrats of making your own sorting algorithm!

Speed/Efficiency

There are plenty of sorts on Wikipedia that are more efficient, if you want to take a look at them. I added rough speed (given random data) and difficulty estimates:

Output

Typically it is bad practice to put a print statement inside a function, because you don't want your console flooded with text if you are calling that function a bunch of times. Instead, you can do return numSort inside your function and print(sortFunc(myList)) outside.

Naming

Now, I'm sure you will also get answers pertaining to variable names, but I'm not a stickler for that, plus your variables and functions seem good already.

Happy coding!

\$\endgroup\$
  • \$\begingroup\$ You may want to add that Bubble sort is linear in the best case (ie very fast). While the others (except insertion) don't have this property. \$\endgroup\$ – Martin York Apr 25 '16 at 21:19
  • \$\begingroup\$ @LokiAstari changed to include random data \$\endgroup\$ – Blue Apr 26 '16 at 2:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.