python: 選擇排序,氣泡排序,插入排序,快速排序
阿新 • • 發佈:2018-11-15
def selectSort(lyst): n = len(lyst) for i in range(n - 1): minindex = i for j in range(i + 1, n): if lyst[j] < lyst[minindex]: minindex = j if minindex != i: lyst[minindex], lyst[i] = lyst[i], lyst[minindex] print(lyst) def bubbleSort(lyst): n = len(lyst) for i in range(n - 1): for j in range(n - i - 1): if lyst[j] > lyst[j + 1]: lyst[j], lyst[j + 1] = lyst[j + 1], lyst[j] print(lyst) def insertSort(lyst): n = len(lyst) for i in range(1, n): temp = lyst[i] j = i - 1 while j >= 0 and temp < lyst[j]: lyst[j + 1] = lyst[j] j = j - 1 lyst[j + 1] = temp print(lyst) def quickSort(lyst): quickSortHelper(lyst, 0, len(lyst) - 1) def quickSortHelper(lyst, left, right): if left < right: pivotLocation = partition(lyst, left, right) quickSortHelper(lyst, left, pivotLocation - 1) quickSortHelper(lyst, pivotLocation + 1, right) def partition(lyst, left, right): middle = (left + right) // 2 pivot = lyst[middle] lyst[middle] = lyst[right] lyst[right] = pivot temp = left for index in range(left, right): if lyst[index] < pivot: lyst[index], lyst[temp] = lyst[temp], lyst[index] temp += 1 lyst[right], lyst[temp] = lyst[temp], lyst[right] return temp if __name__ == '__main__': l = [2, 5, 7, 1, 4, 6, 3, 0] # selectSort(l) # bubbleSort(l) # insertSort(l) quickSort(l) print(l) pass