简体   繁体   English

如何改进 Python 中的排序算法?

[英]How can I improve my sorting algorithm in python?

I wrote a sorting algorithm in python, but I think it looks pretty bad.我用python写了一个排序算法,但我认为它看起来很糟糕。 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.编辑:我知道 list.sort() 函数,但我想自己做。

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.您可以做的最简单有效的方法是使用 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对于某些使用 python 进行排序的具体方法,您可以查看如下内容: https : //www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM