# 快速排序算法——两种写法

xiaoxiao2021-02-28  2

#### 写法一 伪代码：

p,r分别为数组A的首元素和尾元素的下标 主程序直接调用Quicksort(A, 1, n)即可

if p<r then q←Partition(A, p, q-1) //划分数组，找到首元素A[p]在排好序后的位置q A[p]←→A[q] Quicksort(A, p, q-1) Quicksort(A,q+1,r)

Partition(A, p, r) 输入：数组A[p,r] 数组：j, A的首元素在排好序的数组中的位置

x←A[p] i←p j←r+1 while true do repeat jj-1 util A[j]≤x repeat ii+1 until A[i]>x if i < j then A[i]←→A[j] else return j

Python实现代码：

def quicksort(ar, p, r): if p < r: q = partition(ar, p, r) arr[p], arr[q] = ar[q], arr[p] quicksort(ar, p, q - 1) quicksort(ar, q + 1, r) else: return def partition(ar, p, r): x = ar[p] i = p j = r while 1: while ar[j] > x: j = j - 1 while ar[i] <= x: i = i + 1 if i < j: ar[i], ar[j] = ar[j], ar[i] else: return j arr = [1, 4, 7, 1, 5, 5, 3, 85, 34, 75, 23, 75, 2, 0] print "initial array:\n", arr quicksort(arr, 0, len(arr) - 1) print "result array:\n", arr

#### 写法二 伪代码：

QUICKSORT(A, p, r)

if p<r q = PARTITION(A,p,r) QUCIKSORT(A,p,q-1) QUICKSORT(A,q+1,r)

PARTITION(A, p, r)

x = A[r] i = p-1 for j=p to r-1 if A[j]≤x i = i + 1 exchange A[i] with A[j] exchange A[i+1] with A[r] return i+1

Python实现代码

def quicksort(ar, p, r): if p < r: q = partition(ar, p, r) quicksort(ar, p, q - 1) quicksort(ar, q + 1, r) else: return def partition(ar, p, r): x = ar[r] i = p-1 for j in range(p, r): if ar[j] <= x: i = i + 1 ar[i], ar[j] = ar[j], ar[i] ar[i+1], ar[r] = ar[r], ar[i+1] print ar return i+1 arr = [2, 8, 7, 1, 3, 5, 6, 4] print "initial array:\n", arr print "***************************" quicksort(arr, 0, len(arr) - 1) print "***************************" print "result array:\n", arr