并排,快排和冒泡排序
Posted xuan-yu95
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了并排,快排和冒泡排序相关的知识,希望对你有一定的参考价值。
并排
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 4 def 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]
以上是关于并排,快排和冒泡排序的主要内容,如果未能解决你的问题,请参考以下文章