如何使用迭代函数按最小值排序?

发布于 2024-12-11 09:33:29 字数 519 浏览 0 评论 0原文

我的老师希望我做一个算法来按升序排序,但使用列表中的最小数字并将其放在开头。我读了一个数字文件,到目前为止我已经:

  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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半葬歌 2024-12-18 09:33:29

根据您的描述,我推断您的老师希望您实现选择排序算法。您可能想看一下。

在此算法中,您将最小的数字与当前位置交换。最初,当前位置位于列表的开头,并且当您交换值时它会发生变化。

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.

弱骨蛰伏 2024-12-18 09:33:29

这是冒泡排序:

...
for i in range(0, n-1):
    for j in range(i + 1, n):
        if ls[j] < ls[i]:
            temp = ls[i]
            ls[i] = ls[j]
            ls[j] = temp
...

This is bubble sort:

...
for i in range(0, n-1):
    for j in range(i + 1, n):
        if ls[j] < ls[i]:
            temp = ls[i]
            ls[i] = ls[j]
            ls[j] = temp
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文