记录python零基础备战24蓝桥杯,由于个人懒惰,而且容易忘事,所以现以此方式来督促自己学习,在学习算法的过程中,必不可少的就是要学习一些基础算法的实现,对于本文来说,虽然python中自带一些排序函数,如sort函数----list.sort(cmp=None, key=None, reverse=False),sorted函数----sorted(iterable[, cmp[, key[, reverse]]]),但是学习算法的基础实现有利于对算法的深入了解,可以通过学习基础的排序算法来对分治思想有一个大致的了解。(本文只涉及对算法的实现,具体的原理可以参考其他文章,本文不过多展示)
归并排序
def gui(q, l, r):
if l >= r:
return
else:
mid = l + r >> 1
gui(q, l, mid)
gui(q, mid + 1, r)
i, j, tmp = l, mid + 1, []
while i <= mid and j <= r:
if q[i] <= q[j]:
tmp.append(q[i])
i += 1
else:
tmp.append(q[j])
j += 1
while i <= mid:
tmp.append(q[i])
i += 1
while j <= r:
tmp.append(q[j])
j += 1
q[l:l+len(tmp)] = tmp
快速排序
def quicksort(nums, start, end):
if start >= end:
return
left, right = start, end
pivot = nums[(start + end) // 2]
while left <= right:
while left <= right and nums[left] < pivot:
left += 1
while left <= right and nums[right] > pivot:
right -= 1
if left <= right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
quicksort(nums, start, right)
quicksort(nums, left, end)