0

I wrote a sorting algorithm in python, but I think it looks pretty bad. How can I make it better and more efficient?

#lis is the list you want to sort for smallest to biggest
def sortMin(lis):
  output = []
  listen = lis
  for i in range(len(lis)):
    curNum = lis[0]
    curArr = 0
    for j in range(len(lis)):
      if listen[j] < curNum:
        curNum = listen[j]
        curArr = j
    output.append(curNum)
    listen.pop(curArr)
  return output

Edit: I know of the list.sort() function, but I want to make my own.

2
  • 3
    If you want to learn, you can try implementing quicksort. If you want to use builtin library, you can use lst.sort() Commented Oct 13, 2021 at 10:41
  • 1
    "How can I make it better and more efficient?" -- by using the built-in sort Commented Oct 13, 2021 at 10:41

2 Answers 2

1

The are numerous way to do sorting efficiently. The most simplest efficient way that you could do is to use the available sort method in python.

lis = ['c', 'a', 'b']
lis.sort() # This will sort the list in ascending order

If you want to study sorting algorithms then there are may good books on that subject.

For specifically some ways to sort with python then you could checkout something like this: https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm

Sign up to request clarification or add additional context in comments.

2 Comments

I knew of this already but wanted to make my own. Do you have anything I can do to improve my code?
You should avoid using append, it's better to pre-allocate the space you need or just swap the elements within the original list. All the sorting methods in the link I provided swap the elements within the original array. Also, you iterate over the full list twice you can reduce that a bit.
0

This is another "sort function" that improves performance/ readability over yours (avoiding nested loops).

def sortMin(my_list):
    sorted_list = []
    while my_list:
        min_ = my_list [0]
        for x in my_list:
            if x < min_:
                min_= x
        sorted_list.append(min_)
        my_list.remove(min_)
    return sorted_list

Test:

l = [-5, -23, 5, 0, 23, -6, 23, 67]    
sortMin(l)

result:

[-23, -6, -5, 0, 5, 23, 23, 67]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.