使用Python进行选择排序
我(Python DS初学者)在Python中实现了这个SelectionSort()算法,就像我在Java中学习的那样。 使用SelectionSort进行排序是否有更好的方法使用Python进行排序?。 请帮帮我使用Python进行选择排序,python,sorting,selection-sort,Python,Sorting,Selection Sort,我(Python DS初学者)在Python中实现了这个SelectionSort()算法,就像我在Java中学习的那样。 使用SelectionSort进行排序是否有更好的方法使用Python进行排序?。 请帮帮我 def selectionSort(arr,an): for lastUnsortedInteger in range(an-1,0,-1): ma = max(arr[0:lastUnsortedInteger+1]) largest =
def selectionSort(arr,an):
for lastUnsortedInteger in range(an-1,0,-1):
ma = max(arr[0:lastUnsortedInteger+1])
largest = arr.index(max(arr[0:lastUnsortedInteger+1]))
swap(arr,largest,lastUnsortedInteger)
return arr
def swap(arr,ai,aj):
arr[ai],arr[aj] = arr[aj],arr[ai]
if __name__ == '__main__':
an = int(input())
arr = list(map(int,input().strip().split()))
selectionSort(arr,an)
print("Sorted using SelectionSort():\n")
for ai in arr:
print(arr)
这是我的选择排序的实现,它似乎是其他两个实现中最快的
def SelectionSort_2(array): # Fastest implementation
length = len(array)
# Traverse through all array elements
for i in range(length):
# Find the minimum element in remaining unsorted array
min_idx = i
for j in range(i+1, length):
if array[min_idx] > array[j]:
min_idx = j
# Swap the found minimum element with the first element
array[i], array[min_idx] = array[min_idx], array[i]
return array
也许更适合谢谢你的建议@tobias_k只有几点建议:您可以在一行中交换,而无需tmp:
a,b=b,a
,您可以使用min
或max
内置的键来选择要交换的索引。