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.
CodePudding user response:
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
CodePudding user response:
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]