Skip to content

Commit e36af72

Browse files
committed
fix quicksort
1 parent 2db5394 commit e36af72

File tree

2 files changed

+15
-16
lines changed

2 files changed

+15
-16
lines changed

docs/13_高级排序算法/quick_sort.md

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,14 @@
1818

1919
```py
2020
def quicksort(array):
21-
if len(array) < 2: # 递归出口,空数组或者只有一个元素的数组都是有序的
21+
size = len(array)
22+
if not array or size < 2: # NOTE: 递归出口,空数组或者只有一个元素的数组都是有序的
2223
return array
23-
else:
24-
pivot_index = 0 # 选择第一个元素作为主元 pivot
25-
pivot = array[pivot_index]
26-
less_part = [i for i in array[pivot_index+1:] if i <= pivot]
27-
great_part = [i for i in array[pivot_index+1:] if i > pivot]
28-
return quicksort(less_part) + [pivot] + quicksort(great_part)
29-
24+
pivot_idx = 0
25+
pivot = array[pivot_idx]
26+
less_part = [array[i] for i in range(size) if array[i] <= pivot and pivot_idx != i]
27+
great_part = [array[i] for i in range(size) if array[i] > pivot and pivot_idx != i]
28+
return quicksort(less_part) + [pivot] + quicksort(great_part)
3029

3130
def test_quicksort():
3231
import random

docs/13_高级排序算法/quicksort.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22

33

44
def quicksort(array):
5-
if len(array) < 2: # 递归出口,空数组或者只有一个元素的数组都是有序的
5+
size = len(array)
6+
if not array or size < 2: # NOTE: 递归出口,空数组或者只有一个元素的数组都是有序的
67
return array
7-
else:
8-
pivot_index = 0 # 选择第一个元素作为主元 pivot
9-
pivot = array[pivot_index]
10-
less_part = [i for i in array[pivot_index+1:] if i <= pivot]
11-
great_part = [i for i in array[pivot_index+1:] if i > pivot]
12-
return quicksort(less_part) + [pivot] + quicksort(great_part)
8+
pivot_idx = 0
9+
pivot = array[pivot_idx]
10+
less_part = [array[i] for i in range(size) if array[i] <= pivot and pivot_idx != i]
11+
great_part = [array[i] for i in range(size) if array[i] > pivot and pivot_idx != i]
12+
return quicksort(less_part) + [pivot] + quicksort(great_part)
1313

1414

1515
def test_quicksort():
@@ -23,7 +23,7 @@ def quicksort_inplace(array, beg, end): # 注意这里我们都用左闭右
2323
if beg < end: # beg == end 的时候递归出口
2424
pivot = partition(array, beg, end)
2525
quicksort_inplace(array, beg, pivot)
26-
quicksort_inplace(array, pivot+1, end)
26+
quicksort_inplace(array, pivot + 1, end)
2727

2828

2929
def partition(array, beg, end):

0 commit comments

Comments
 (0)