Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python进行选择排序_Python_Sorting_Selection Sort - Fatal编程技术网

使用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 =

我(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 = 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
内置的
键来选择要交换的索引。