并排
class mergeSort: def mergeSort(self, A): self.mSort(A, 0, len(A)-1) def mSort(self, A, lo, hi): if lo < hi: mid = (lo+hi)//2 self.mSort(A, lo, mid) self.mSort(A, mid+1, hi) self.merge(A, lo, mid, hi) def merge(self, A, lo, mid, hi): l = A[lo:mid+1] r = A[mid+1:hi+1] l.append(float("inf")) r.append(float("inf")) i, j = 0, 0 for k in range(lo, hi+1): if l[i] <= r[j]: A[k] = l[i] i+=1 else: A[k] = r[j] j+=1
快排
class quickSort: def quickSort(self, A): self.qSort(A, 0, len(A)-1) def qSort(self, A, lo, hi): if lo < hi: p = self.partition(A, lo, hi) self.qSort(A, lo, p-1) self.qSort(A, p+1, hi) def partition(self, A, lo, hi): pivot = A[hi] A[hi], A[lo] = A[lo], A[hi] bound = lo for i in range(lo, hi+1): if A[i] < pivot: bound += 1 A[bound], A[i] = A[i], A[bound] A[lo], A[bound] = A[bound], A[lo] return bound
冒泡排序
#1 4 3 2#1 3 2 4#1 2 3 4def bubble_sort1(A): for i in range (0, len(A) - 1): for j in range (0, len(A) - i - 1): if A[j] > A[j+1]: A[j], A[j+1] = A[j+1], A[j]