首页 > 其他分享 >快速排序和堆排序

快速排序和堆排序

时间:2022-08-13 19:47:21浏览次数:90  
标签:arr now 堆排序 head high low 排序 快速

python快速排序、堆排序、计数排序、桶排序、基数排序_一只什么都不懂的码农的博客
常用排序算法总结和对比_玖玖拾月陆的博客-CSDN博客_各种排序算法的总结和比较
image

#快速排序(自己做过优化的结果)
import random
def quickSort(arr, head,tail):
	if head >= tail:
		return arr
	mid = head + random.randint(0,tail - head)
	pivot = arr[mid]
	arr[mid] = arr[head]
	low = head
	high = tail
	while low != high:
		while low < high and arr[high] >= pivot:
			high -= 1
		arr[low] = arr[high]
		while low < high and arr[low] <= pivot:
			low += 1
		arr[high] = arr[low] 

	arr[low] = pivot
	quickSort(arr, head, low - 1)
	quickSort(arr, low + 1, tail)
	return arr

if __name__ == '__main__':
	arr = list(map(int,input().strip().split()))
	kk = quickSort(arr,0,len(arr)-1)
	print(kk)
#堆排序
def buildMaxHeap(arr):
    import math
    for i in range(math.floor(len(arr)/2),-1,-1):
        heapify(arr,i)
def heapify(arr, i):
    min1 = 2*i+1
    max1 = 2*i+2
    now = i
    if min1 < leng and arr[min1] > arr[now]:
        now = min1
    if max1 < leng and arr[max1] > arr[now]:
        now = max1
    if now != i:
        swap(arr, i, now)
        heapify(arr, now)
def swap(arr, i, j):
    arr[i], arr[j] = arr[j], arr[i]
def heapSort(arr):
    global leng
    leng = len(arr)
    buildMaxHeap(arr)
    for i in range(len(arr)-1,0,-1):
        swap(arr,0,i)
        leng -=1
        heapify(arr, 0)
    return arr
arr = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]
print(heapSort(arr))

标签:arr,now,堆排序,head,high,low,排序,快速
From: https://www.cnblogs.com/chuqianyu/p/16583865.html

相关文章

  • MySQL中IN()按照指定列指定规则排序
    现在我有这么一个需求,我需要通过IN(id1,id2,......)查询id字段,并且id字段按照IN()中的顺序排序例如:IN(5,1,2,4)===>查询出来的结果也应该为5,1,2,4#普通写法按照......
  • 记一次电脑内存快速爆满
    1.公司给配了新电脑,没到俩个月,我分出的D盘一下子就爆满了,用了360和win11存储过滤了本地,显示是我平时安装软件目录占用了2.360大文件查找和win存储都没定位到具体的文件夹......
  • 字符串排序算法
    字符串排序算法:键索引计数法低位优先的字符串排序算法(Least-Significant-Digit-First,LSD)高位优先的字符串排序算法(MSD)三向字符串快速排序键索引计数法适用性:适用......
  • Java中list集合自定义排序-2022新项目
    一、业务场景为了加快首页数据查询的效率,因此将首页查询的数据大多数都放在了缓存中,包括各种list集合数据。对这些从缓存中获取的数据做了一个兜底处理,如果从缓存中......
  • Spark中group_concap替换函数concat_ws,collect_set-实现数分组后,将分组后字段连接排序
    group_concat可以在mysql中group_concat(distinctpap_srcorderbydata_date)hive中group_concat函数只能分组后连接起来,不能orderbydata_date排序spark中用conca......