快递排序的第一种思想(以下都以升序为例):假设一个数组a, 设置一个基准数povit,然后两个指针分别指向数组的开始和结束,假设为i, j从j开始往前走,走到小于povit值得时候停下来,然后i从前往后走,走到大于povit的位置停下来,当i < j的时候进行交换,依次进行,知道i==j的停下来, 然后再交换povit和a[i]的值,最后递归处理[start, i - 1], [i + 1, end]。
show the code:
def quicksort(a, start, end):
if start >= end:
return
i,j = [start, end]
povit = a[start]
while i < j:
while i < j and a[j] >= povit:
j -= 1
while i < j and a[i] <= povit:
i += 1
if i != j:
a[i], a[j] = a[j], a[i]
a[i], a[start] = a[start], a[i]
quicksort(a, start, i - 1)
quicksort(a, i + 1, end)
a = [5,2,6,1,3]
quicksort(a, 0, len(a) - 1)
print(a)
接下来思考,单链表的快速排序怎么做呢?单链表只能够从前往后走,如果按照快速排序的思想,就是说,只能从前往后走,然后划分一个比基准数小的位置,和比基准数大的位置,可以用i, j两个指针表示,i表示前i个数都是比基准数小的,j用来遍历,当a[j] < 基准数povit的时候,i++,然后交换a[j],a[i];j++
show the code:
def quicksort(a, start, end):
if start >= end:
return
i,j = start, start + 1
pivot = a[start]
while j < end:
if a[j] < pivot:
i += 1
a[i], a[j] = a[j], a[i]
j += 1
a[start], a[i] = a[i], a[start]
quicksort(a, start, i)
quicksort(a, i + 1, end)
a = [5,8,4,3,2,5,7,9]
quicksort(a,0,len(a))
print(a)
单链表的形式思路类似,show the code:
class node:
def __init__(self, val):
self.val = val
self.next = None
root = node(5)
p = root
p.next = node(8)
p = p.next
p.next = node(4)
p = p.next
p.next = node(3)
p = p.next
p.next = node(2)
p = p.next
p.next = node(5)
p = p.next
p.next = node(7)
p = p.next
p.next = node(9)
def print_list(root):
while root:
print(root.val, end = ' ')
root = root.next
def singlelist_quicksort(begin, end):
if begin == end :
return
p, q = begin, begin.next
pivot = begin.val
while q:
if q.val < pivot:
p = p.next
p.val, q.val = q.val, p.val
q = q.next
begin.val, p.val = p.val, begin.val
singlelist_quicksort(begin, p)
singlelist_quicksort(p.next, end)
# print_list(root)
singlelist_quicksort(root,None)
print_list(root)
时间复杂度都是O(N log N)