选择排序问题

时间:2017-01-29 17:35:33

标签: python function sorting selection built-in

我试图在python中创建一个简单的选择排序程序,而不使用任何内置函数。我现在的问题是我的代码只是排序列表的第一个数字。怎么了?

这是我的排序

crossDomain: true,
 xhrFields: { withCredentials: true }

这是我使用

的最小和交换功能
  def selectionsort(list1):
    for x in range(len(list1)):
      tiniest = minimum(list1)
      swap(tiniest,x,list1)
  return(list1)

输出的一个例子 列表= [3,2,1,0]

输出= [0,2,1,3]

2 个答案:

答案 0 :(得分:1)

一些简化会使其更具可读性/可理解性:

def swap(lst, i1, i2):
  lst[i1], lst[i2] = lst[i2], lst[i1]  # easy-swapping by multi assignment 

def minimum(lst, s):  # s: start index
  min_val, min_index = lst[s], s
  for i in range(s+1, len(lst)):
    if lst[i] < min_val:
      min_val, min_index = lst[i], i
  return min_index  # return index of minimum, not minimum itself

def selection_sort(lst):
  for i in range(len(lst)): 
    swap(lst, i, minimum(lst, i))  
    # find min index starting from current and swap with current

答案 1 :(得分:0)

似乎minimum返回list1中最小元素的值,但您的swap需要索引。尝试使minimum返回索引而不是最小元素的值。

相关问题