python 常見排序實例

使用Python 基礎排序算法設計,冒泡排序,插入排序,快速排序...python

需求

對一組無序數據進行排序算法設計,要求以下:算法

輸入:[1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]app

輸出:[1, 3, 5, 5, 22, 23, 34, 34, 37, 74, 75, 86, 456]ui

冒泡排序

核心算法:循環比較相鄰的兩個元素,若是前面一個元素比後面一個元素大,則交換位置。設計

#!/usr/bin/env python 
# -*- coding: utf-8 -*-


def bubble_sort(data_source):
    length = len(data_source)
    for i in range(1, length):
        for j in range(length - i):
            if data_source[j] > data_source[j + 1]:
                data_source[j], data_source[j + 1] = data_source[j + 1], data_source[j]
    return data_source


if __name__ == '__main__':
    test_array = [1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]
    print bubble_sort(test_array)

插入排序

核心算法:從頭至尾循環,對於未排序數據,在已排序序列中從後向前掃描,找到相應位置並插入,於是在從後向前掃描過程當中,須要反覆把已排序元素逐步向後挪位,爲最新元素提供插入空間。blog

#!/usr/bin/env python 
# -*- coding: utf-8 -*-


def insert_sort(data_source):
    count = len(data_source)
    for i in range(1, count):
        key = data_source[i]
        j = i - 1
        while j >= 0:
            if data_source[j] > key:
                data_source[j], data_source[j + 1] = key, data_source[j]
            j -= 1
    return data_source

if __name__ == '__main__':
    test_array = [1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]
    print insert_sort(test_array)

 快速排序

核心算法:每次循環,取一個基數,將序列分紅三部分:比基數小的數序列,基數,比基數大的序列。不斷重複對每一個序列進行相同的處理,直到每一個序列爲空,則完成排序排序

#!/usr/bin/env python 
# -*- coding: utf-8 -*-


def quick_sort(data_source):
    length = len(data_source)
    if length == 0:
        return []
    else:
        left = []
        right = []
        for i in range(1, length):
            if data_source[0] > data_source[i]:
                left.append(data_source[i])
            else:
                right.append(data_source[i])
        return quick_sort(left) + [data_source[0]] + quick_sort(right)

if __name__ == '__main__':
    test_array = [1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]
    print quick_sort(test_array)
相關文章
相關標籤/搜索