【问题标题】:Selection Sort in Python not sortingPython中的选择排序不排序
【发布时间】:2020-03-12 20:26:24
【问题描述】:

我编写了一个选择排序程序,首先创建了一个查找数组中最小元素的函数。然后我遍历数组,将最小元素放置在数组中的正确位置,同时替换最小元素。 这是我的代码:

a=[int(input()) for _ in range(6)]
def smallest_element(arr,x):
    smallest = arr[x]
    d = x
    for j in range(x+1,len(arr)):
        if arr[j] < smallest:
            smallest = arr[j]
            d = j
    return d
for i in range(0,len(a)):
    c = a[i]
    if(c > a[smallest_element(a,i)]):
        a[i] = a[smallest_element(a,i)]
        a[smallest_element(a,i)] = c
print(a)

但问题是我的数组没有排序。
输入 - [5,2,4,6,1,3]
输出 - [5,2,4,6,1,3]

【问题讨论】:

    标签: python-3.x sorting selection-sort


    【解决方案1】:

    错误似乎在您的循环中。

    您将找到的最小值分配给当前索引。

    a[i] = a[smallest_element(a,i)]
    

    然后将最初存储的值分配给最小元素所在的索引。

    a[smallest_element(a,i)] = c
    

    但是,您确实会重新计算最小元素的索引,该索引始终是当前索引 - 因为您只是将最小值复制到当前索引。

    第一种方法

    我知道这个问题有两种解决方案。首先,您只能在每个循环轮次中搜索最小元素的索引。这样您就不会重新计算索引并写入正确的位置。

    for i in range(0, len(a)):
        c = a[i]
        indexOfSmallestElement = smallest_element(a, i)
        smallestElement = a[indexOfSmallestElement]
    
        if c > smallestElement:
            a[i] = smallestElement
            a[indexOfSmallestElement] = c
    

    第二种方法

    另一种解决方案是从当前索引 + 1 而不是当前索引开始搜索元素,从而跳过您已经更改的条目。

    a[smallest_element(a, i)] = ca[smallest_element(a, i + 1)] = c 交换。

    但我建议使用第一种方法,因为它会减少数组迭代的次数。

    【讨论】:

      【解决方案2】:

      首先,在您的代码中,您调用了 minimum_element(arr,x) 3 次,这将花费更多时间用于更大的数组。相反,我们可以将该值存储到一个变量中,而不是调用 3 次。

      其次,您要交换 2 次 一个在函数体中在 if 块中

      所以在函数体中,找到当前最小的元素。然后将该索引返回给 main。然后如果它小于当前元素(在 main for 循环中),则交换它。

      #Find the smallest element
      def smallest_element(arr,x):
          small = x
          for j in range(x+1,len(arr)):
              if arr[j] < arr[small]:
                  small=j
          return small
      
      #now compare  it with the current element  
      for i in range(0,len(a)):
          c = a[i]
          curr=smallest_element(a,i)
      
          if(c > a[curr] and curr!=i):
              a[i] = a[curr]
              a[curr] = c
      
      
          print(a)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-19
        • 1970-01-01
        • 1970-01-01
        • 2013-04-25
        • 2019-09-16
        • 2015-08-13
        • 1970-01-01
        相关资源
        最近更新 更多