排序 快速排序 Python

2021-08-06 01:52:47 字數 2544 閱讀 9825

快速排序(快排)是非常常用的排序方法,在技術面試中出現頻率也特別高。它主要採用交換和分治的策略進行排序。是不穩定排序。

步驟:

1、在序列中選乙個元素作為劃分的基準元素(pivot)

2、將所有不大於pivot的數字放在pivot的前面,大於pivot的數字放在pivot的後面

3、以pivot為界,對前後兩個子串行分別遞迴重複前兩步,直至區間內只有乙個元素

對序列 [2, 4, 7, 3, 6, 5] 按公升序排列,取倒數第乙個元素為pivot,tail表示不大於pivot的序列的最後乙個數的下標,所以最後基準元素的下標為tail + 1

pivot

tail

排序過程5-1

[2, 4, 7, 3, 6, 5]50

[2, 4, 7, 3, 6, 5]51

[2,4, 7, 3, 6, 5]51

[2, 4,7, 3, 6, 5]52

[2, 4,7,3, 6, 5] -> [2, 4,3,7, 6, 5]52

[2, 4, 3,7,6, 5]52

[2, 4, 3,5, 6,7] (交換下標為tail+1的元素和pivot)

至此,前後兩個子串行劃分完畢,下面繼續對子序列進行排序

pivot

tail

排序過程3-1

[2, 4, 3]30

[2, 4, 3]30

[2,4, 3]30

[2,3,4] (交換下標為tail+1的元素和pivot)

pivot

tail

排序過程7-1

[6, 7]70

[6, 7]70

[6,7] (交換下標為tail+1的元素和pivot)

class

solution:

# @param a an integer array

# @return nothing

defsortintegers2

(self, a):

# write your code here

if a is

none

or len(a) <= 1:

return

s = 0

e = len(a) - 1

self.quicksort(a, s, e)

defquicksort

(self, a, s, e):

if s < e:

# 基準元素下標

pivot_ind = self.partition(a, s, e)

self.quicksort(a, s, pivot_ind - 1)

self.quicksort(a, pivot_ind + 1, e)

defpartition

(self, a, s, e):

# 選取倒數第乙個元素為基準元素

pivot = a[e]

# tail表示不大於pivot的序列的最後乙個數的下標,所以最後基準元素的下標為tail + 1

tail = s - 1

for i in range(s, e):

if a[i] <= pivot:

tail += 1

self.swap(a, i, tail)

self.swap(a, tail + 1, e)

return tail + 1

defswap

(self, a, i, j):

if i != j:

tmp = a[i]

a[i] = a[j]

a[j]= tmp

選取第乙個元素為基準元素

def

partition

(self, a, s, e):

# 選取第乙個元素為基準元素

pivot = a[s]

# tail表示不小於pivot的序列的第乙個數的下標,所以最後基準元素的下標為tail - 1

tail = e+1

for i in range(e, s,-1):

if a[i] >= pivot:

tail -= 1

self.swap(a, i, tail)

self.swap(a, tail - 1 , s)

return tail - 1

快排的時間複雜度比較穩定,為o(

nlog

n)

python快速排序排序 python快速排序

import random def rand n for i in range n yield random.randint 0,1000 建立乙個隨機數列表 def createlist n lists for i in rand n return lists 挖坑法快速排序 def quick ...

python快速排序

coding utf 8 class quicksort def sort self,list,left,right 開始位置小於 位置 if left 取到中間的乙個下標值 s list left right 2 i 0 i left j 下標結束 j right while true 從開始位置...

python快速排序

import random def rand n for i in range n yield random.randint 0,1000 建立乙個隨機數列表 def createlist n lists for i in rand n return lists 挖坑法快速排序 def quick ...