单链表的快排和普通快排都是快排
1.移动数(partition),使得左边的都小于key, 右边的都大于key
2.反复
下面是正常数组的快排:
def arr_sort(self, vector,start, end):
#start, end = 0, len(vector)-1
i,j = start ,end
if i>=j:
return
key = vector[start]
while i<j:
while i<j and vector[j]>= key:
j-=1
vector[i] = vector[j]
while i<j and vector[i] <= key:
i+=1
vector[j] = vector[i]
vector[j] = key
self.arr_sort(vector, start,i-1)
self.arr_sort(vector, j+1, end)
单链表的快排需要重写partition:
def partition(self, head, end):
p = head
q = p.next
key = head.val
while q !=end:
if q.val < key:
p = p.next
p.val, q.val = q.val, p.val
q = q.next
p.val, head.val = head.val, p.val
return p
def list_sort(self,head, end):
p = self.partition(head, end)
self.list_sort(head,p)
self.list_sort(p.next,end)