sort & search algorithm


def quick_sort(array):
    if len(array) < 2:
        return array
    else:
        pivot_index = 0
        pivot = array[pivot_index]
        less_part = [i for i in array[pivot_index+1:] if i < pivot]
        greater_part = [i for i in array[pivot_index+1:] if i >= pivot]
        return quick_sort(less_part)+[pivot]+quick_sort(greater_part)


def merge_sort(array):
    if len(array) < 2:
        return array
    mid = int(len(array)/2)
    sorted_left_part = merge_sort(array[:mid])
    sorted_right_part = merge_sort(array[mid:])
    return merge_sorted_array(sorted_left_part, sorted_right_part)


def merge_sorted_array(a, b):
    i = j = 0
    sorted_array = []
    while i < len(a) and j < len(b):
        if a[i] < b[j]:
            sorted_array.append(a[i])
            i = i + 1
        else:
            sorted_array.append(b[j])
            j = j + 1
    if i < len(a):
        sorted_array.extend(a[i:])
    else:
        sorted_array.extend(b[j:])
    return sorted_array


def heap_sort(array):
    from heapq import heappop, heappush
    items = []
    for value in array:
        heappush(items, value)
    return [heappop(items) for i in range(len(items))]


def binary_search(sorted_array, value):
    if not sorted_array:
        return -1

    begin = 0
    end = len(sorted_array) - 1
    while begin <= end:
        mid = int((begin + end) / 2)
        if sorted_array[mid] == value:
            return mid
        elif sorted_array[mid] < value:
            begin = mid + 1
        else:
            end = mid - 1
    return -1


def test_sort():
    import random
    ll = list(range(10))
    random.shuffle(ll)
    print(ll)
    #sorted_ll = quick_sort(ll)
    #sorted_ll = merge_sort(ll)
    sorted_ll = heap_sort(ll)
    print(sorted_ll)
    assert sorted_ll == sorted(ll)


def test_search():
    sorted_ll = [0, 1, 2, 3]
    print(sorted_ll)
    rtv = binary_search(sorted_ll, 5)
    print(rtv)
    rtv = binary_search(sorted_ll, 1)
    print(rtv)
    return


if __name__ == '__main__':
    test_sort()
    test_search()

Todo: time complexity & space complexity analytical method

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章