[算法学习]20150414.3.快排

快排实现

# -*-coding: utf-8 -*-
import string
import random


def adjustArray(array, l, r):
    """quick sort one step"""
    if not array or l < 0 or r < 0 or l > r:
        return

    i, j = l, r
    base = array[l]

    while i < j:
        while i < j and array[j] >= base:
            j -= 1

        if i < j:
            array[i] = array[j]
            i += 1

        while i < j and array[i] < base:
            i += 1

        if i < j:
            array[j] = array[i]
            j -= 1

    array[i] = base
    return i


def quick_sort(datas, l, r):
    """recurison quick sort"""
    if l < r:
        i = adjustArray(datas, l, r)
        quick_sort(datas, l, i - 1)
        quick_sort(datas, i + 1, r)


if __name__ == '__main__':
    datas = list([random.randint(1, 100) for i in range(10)])
    print datas
    quick_sort(datas, 0, 9)
    print datas
点赞