Python - Quick Sort

import random

def partion(arr, l, r):
    '''
    Divid the array
    The left part is less than the pivot
    The right part is greater than the pivot
    Then return the position of pivot

    '''

    i = l #i points to the END of left part
    j = l + 1 #j points to the END of right part
    x = arr[l]  #pick the first one as pivot or pick it ramdomly
    while j <= r:  #quit the loop if j is out of the array
        while j <= r and arr[j] >= x: #look for the element less than the pivot
            j= j + 1

        if j <= r: # it is found
            arr[i+1], arr[j] = arr[j], arr[i+1] #swap with the one after i
            j = j + 1 # we have one added to left, move to the next
            i = i + 1 # move one to check the next element
    arr[l], arr[i] = arr[i], arr[l] #divided by pivot
    return i

def partion2(arr, l, r):
    '''
    This one seems easier to understand
    '''
    i = l
    j = r
    x = arr[l]
    
    while i < j:
        while i < j and arr[j] > x:#scan from right to left
            j = j - 1
        arr[i] = arr[j] #put it to the left
        while i < j and arr[i] <= x: #scan from left to right
            i = i + 1
        arr[j] = arr[i] #put it to the right
    arr[i] = x #at this time i must equal to j
    return i

def quick_sort(arr, l, r):
    if l < r: #condiction to quit, no need to sort
        m = partion(arr, l, r)
        quick_sort(arr, 0, m - 1) #sort the left part
        quick_sort(arr, m + 1, r) #sort the right part

if __name__ == '__main__':
    sample = [random.randrange(0, 100, 1) for i in range(10)]
    original = sample[:]
    print('Before: %s'%original)
    quick_sort(sample, 0, len(sample)-1)
    print('After: %s'%sample)
    print('Corrected: %s'%(sample == sorted(original)))

    

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值