快速排序原理及Python代码实现

【原理】
快速排序的算法就是以每轮都以某种方式选择一个基准数据,然后为基准数据找到其正确的索引位置。
【过程】

每一轮:
	选择一个基准数据,比如temp=array[0]
	start=0, end=len(array)-1
	while start<end:
		从后往前扫描,当array[end]>temp时,end-=1
		array[start]=array[end],这样做的目的是把比基准数据小的数字放在基准数据的前面
		从前往后扫描,若array[start]<temp,则start+=1
		array[end]=array[start],这样做的目的是把比基准数据大的数字放在基准数据的后面
	直到start=end时,将基准数据赋给array[start],基准数据的索引为start

【代码实现】
整个快速排序过程用Python实现如下:

def GetIndex(array, start, end):
    temp = array[start]
    while start < end :
        while array[end] > temp and start < end:
            end -= 1
        array[start] = array[end]
        while array[start] < temp and start < end:
            start += 1
        array[end] = array[start]
    array[start] = temp
    return start
    
def QuickSort(array, start, end):
    if start < end:
        idx = GetIndex(array, start, end)
        QuickSort(array, start, idx-1)
        QuickSort(array, idx+1, end)
发布了24 篇原创文章 · 获赞 0 · 访问量 245

猜你喜欢

转载自blog.csdn.net/qq_36643449/article/details/104473864