# Python 实现快速排序、冒泡排序和选择排序

. 快速排序

<pre class="" style="margin: 0px; padding: 0px 0.5em; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;">

<pre style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important; font-size: inherit; color: inherit; line-height: inherit;">

# quicksort

import random
def quicksort(seq):
if len(seq) < 2:
return seq
else:
base = seq[0]
left = [elem for elem in seq[1:] if elem < base]
right = [elem for elem in seq[1:] if elem > base]
return quicksort(left) + [base] + quicksort(right)
seq = [9, 8, 7, 6, 5, 4, 3]
random.shuffle(seq)

# seq：[6, 4, 9, 3, 8, 5, 7]

print(quicksort(seq))

# 输出：[3, 4, 5, 6, 7, 8, 9]

</pre>

</pre>

image

2. 冒泡排序

<pre class="" style="margin: 0px; padding: 0px 0.5em; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;">

<pre style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important; font-size: inherit; color: inherit; line-height: inherit;">

def bouble_sort(sequence):
seq = sequence[:]
length = len(seq) - 1
i = j = 0
flag = 1
while i < length:
j = 0
while j < length - i:
if seq[j] > seq[j + 1]:
seq[j], seq[j + 1] = seq[j + 1], seq[j]
flag = 0
j += 1
if flag:
break
i += 1
return seq

</pre>

</pre>

image

3. 选择排序

<pre style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important; font-size: inherit; color: inherit; line-height: inherit;">

<pre style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important; font-size: inherit; color: inherit; line-height: inherit;">

def find_minimal_index(seq):
min_elem = seq[0]
count = 0
min_elem_index = count
for elem in seq[1:]:
count += 1
if elem < min_elem:
elem, min_elem = min_elem, elem
min_elem_index = count
return min_elem_index

def select_sort(sequence):
# 选择排序
seq = sequence[:]
length = len(seq)
for i in range(length):
index = find_minimal_index(seq[i:])
seq[index + i], seq[i] = seq[i], seq[index + i]
return seq

</pre>

</pre>