[英]How can I improve my sorting algorithm in python?
我用python寫了一個排序算法,但我認為它看起來很糟糕。 我怎樣才能讓它更好更高效?
#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
編輯:我知道 list.sort() 函數,但我想自己做。
有多種方法可以有效地進行排序。 您可以做的最簡單有效的方法是使用 python 中可用的排序方法。
lis = ['c', 'a', 'b']
lis.sort() # This will sort the list in ascending order
如果您想學習排序算法,那么可能有關於該主題的好書。
對於某些使用 python 進行排序的具體方法,您可以查看如下內容: https : //www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm
這是另一個“排序功能”,可以提高您的性能/可讀性(避免嵌套循環)。
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
測試:
l = [-5, -23, 5, 0, 23, -6, 23, 67]
sortMin(l)
結果:
[-23, -6, -5, 0, 5, 23, 23, 67]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.