如何使用迭代函数按最小值排序?
我的老师希望我做一个算法来按升序排序,但使用列表中的最小数字并将其放在开头。我读了一个数字文件,到目前为止我已经:
def findMin(ls, n):
m = 0
for i in range(1, n): #n is length
if ls[i]<ls[m]:
m = i
return m
def sortlist(ls,n):
if n == 1:
return
m = findMin(ls,n)
ls.insert(0,m)
ls.remove(m)
sortlist(ls, n)
我已经尝试了几种技术,但无法使其发挥作用。我试图将最小数字放在开头,然后从列表中减去它,以便该函数不会将其计入长度。我知道如果我按最大值排序我会输入 n-1 但我应该输入最小值什么呢?
My teacher wants me to do an algorithm to sort in ascending order but by using the minimum number in a list and putting it at the beginning. I read a file of numbers and so far I have:
def findMin(ls, n):
m = 0
for i in range(1, n): #n is length
if ls[i]<ls[m]:
m = i
return m
def sortlist(ls,n):
if n == 1:
return
m = findMin(ls,n)
ls.insert(0,m)
ls.remove(m)
sortlist(ls, n)
I've tried several techniques and can't get it to work. I was trying to put the minimum number at the beginning then minus it from the list so that the function would not count it in the length. I know if I was sorting by maximum I would put n-1 but what do I put for minimum?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您的描述,我推断您的老师希望您实现选择排序算法。您可能想看一下。
在此算法中,您将最小的数字与当前位置交换。最初,当前位置位于列表的开头,并且当您交换值时它会发生变化。
From your description what I deduced is that your teacher wants you to implement Selection Sort algorithm. You may want to have a look at it.
In this algorithm, you swap the least number with the current position. Initially the current position is at the beginning of the list and it shifts as you swap values.
这是冒泡排序:
This is bubble sort: