快速排序-数组
def partition(arr,low,high):
i = ( low-1 ) # 最小元素索引
pivot = arr[high]
for j in range(low , high):
# 当前元素小于或等于 pivot
if arr[j] <= pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
# arr[] --> 排序数组
# low --> 起始索引
# high --> 结束索引
# 快速排序函数
def quickSort(arr,low,high):
if low < high:
pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
链表快排
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def partition(start, end):
node = start.next.next
pivotPrev = start.next
pivotPrev.next = end
pivotPost = pivotPrev
while node != end:
temp = node.next
if node.val > pivotPrev.val:
node.next = pivotPost.next
pivotPost.next = node
elif node.val < pivotPrev.val:
node.next = start.next
start.next = node
else:
node.next = pivotPost.next
pivotPost.next = node
pivotPost = pivotPost.next
node = temp
return [pivotPrev, pivotPost]
def quicksort(start, end):
if start.next != end:
prev, post = partition(start, end)
quicksort(start, prev)
quicksort(post, end)
newHead = ListNode(0)
newHead.next = head
quicksort(newHead, None)
return newHead.next
堆排序
def heapify(arrays,current,size):
if current<size:
left = 2*current+1
right = 2*current+2
vmax = current
if left<size:
if arrays[left]>arrays[vmax]:
vmax=left
if right<size:
if arrays[right]>arrays[vmax]:
vmax=right
if vmax!=current:
arrays[vmax],arrays[current]=arrays[current],arrays[vmax]
heapify(arrays,vmax,size)
def maxheapify(arrays,size):
for i in range(size-1,-1,-1):
heapify(arrays,i,size)
def heap(arrays):
for i in range(len(arrays)):
maxheapify(arrays,len(arrays)-i)
arrays[0],arrays[len(arrays)-i-1] = arrays[len(arrays)-i-1],arrays[0]
arrays = [1,88,0,1,3,2,5,6,7]
heap(arrays)
print(arrays)