Python3&資料結構之選擇排序
阿新 • • 發佈:2018-11-30
第一種寫法:來自演算法圖解
def findSmallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1,len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selectionSort(arr): newArr = [] for i in range(len(arr)): smallest = findSmallest(arr) newArr.append(arr.pop(smallest)) return newArr if __name__ == '__main__': test = [49, 38, 65, 97, 76, 13, 27, 49] print(selectionSort(test))
第二種寫法:
def select_sort(arr): for i in range(len(arr)): m = i for j in range(i,len(arr)): if arr[j]<arr[m]: m = j arr[i],arr[m] = arr[m],arr[i] return arr if __name__ == '__main__': test = [49, 38, 65, 97, 76, 13, 27, 49] print(select_sort(test))
時間複雜度:O(n^2)