Data structure and algorithm Python to achieve quick sort

Quick sort is divided into three steps

  • Select the reference value, pirot divides the array into two word arrays, the elements smaller than the reference value and the elements that are aligned with the large sentence. This process is called prtition
  • Sort these two arrays
  • Merge result
def quicksort(array):
    #当排序的数组小于2就不排序
    if len(array) < 2:
        return array
    else:
        #定一下标
        pivot_index=0
        #取到值
        pivot = array[pivot_index]
        #小于他的值给less_part
        less_part = [i for i in array[pivot_index+1 :] if i <= pivot]
        #大于的值给great_part
        great_part = [i for i in array[pivot_index+1 :] if i > pivot]
        #注意这里的递归参数传的是小于分割点的集合
        return quicksort(less_part)+[pivot]+quicksort(great_part)

def test_quicksort():
    #生成随机数
    import  random
    #创建一个新的list
    seq = list(range(10))
    #随机取出seq
    random.shuffle(seq)
    #assert 测试一个线程 ,sorted返回一个新的list
    assert quicksort(seq) == sorted(seq)
#找到最合适分割值
def partition(array,beg ,end):
    pivot_index = beg
    pivot = array[pivot_index]
    left = pivot_index + 1
    right = end - 1

    while True:
        while left <= right and array[left] < pivot:
            left += 1
        while right >= left and array[right] >= pivot:
            right -= 1
        if left > right:
            break
        else:
            array[left],array[right] = array[right],array[left]
    array[pivot_index],array[right] = array[right],array[pivot_index]
    return right

Guess you like

Origin blog.csdn.net/weixin_44865158/article/details/100798488