你好,我一直在努力实现这种选择排序已经有好几天了。我觉得我的代码很接近它,但无法弄清楚为什么我没有得到它。
这是我的代码
def selectionSort(aList):
#For each index in the list...
for i in range(len(aList)):
#Assume first that current item is already correct...
minIndex = i
#For each index from i to the end...
for j in range(i + 1, len(aList)):
if aList[j] >= aList[j - 1]:
break
aList[j], aList[j - 1] = aList[j - 1], aList[j]
minIndex = aList.index(aList[j - 1])
#Save the current minimum value since we're about
#to delete it
minValue = aList[minIndex]
#Delete the minimum value from its current index
del aList[minIndex]
#Insert the minimum value at its new index
aList.insert(i, minValue)
#Return the resultant list
return aList
这是我得到的结果
[4, 2, 1, 3, 5]
而不是:
[1, 2, 3, 4, 5]
感谢您的提前帮助
答案 0 :(得分:0)
for j in range(i + 1, len(aList)):
if aList[j] >= aList[j - 1]:
break
aList[j], aList[j - 1] = aList[j - 1], aList[j]
minIndex = aList.index(aList[j - 1])
选择排序是通过迭代地找到列表中的最小元素来进行排序。只需将第一个元素设置为最小值,遍历列表,如果当前元素小于最小值,则将其记录为最小值并记录其索引。之后的部分是正确的。
答案 1 :(得分:0)
以下是工作代码人员:
def selectionSort(aList):
#For each index in the list...
for i in range(len(aList)):
minIndex = i
#For each index from i+1 to the end...
for j in range(i + 1, len(aList)):
if aList[minIndex] > aList[j]:
minIndex = j
#Save the current minimum value since we're about
#to delete it
minValue = aList[minIndex]
#Delete the minimum value from its current index
del aList[minIndex]
#Insert the minimum value at its new index
aList.insert(i, minValue)
#Return the resultant list
return aList
再次感谢。 不能相信只有两行代码给了我一个噩梦。 pheew
答案 2 :(得分:0)
你不需要删除和插入,只需交换em!
import System.IO
readListOfLists :: Handle -> IO [[Int]]
readListOfLists handle = do
contents <- hGetContents handle
let ls :: [String]
ls = lines contents
ws :: [[String]]
ws= map words ls
res :: [[Int]]
res = map (map read) ws
return res;