十大经典排序算法Python版

import time


def bubble_sort(array):
    t1 = time.clock()
    for i in range(len(array)):
        for j in range(len(array) - 1 - i):
            if array[j] > array[j + 1]:
                tmp = array[j]
                array[j] = array[j + 1]
                array[j + 1] = tmp
    print('1.冒泡排序\n结果:{}, \n耗时:{}'.format(array, round(time.clock() - t1, 8)))
    return array


def select_sort(array):
    t1 = time.clock()
    for i in range(len(array)):
        min_ind = i
        for j in range(i, len(array)):
            if array[j] < array[min_ind]:
                min_ind = j
        tmp = array[i]
        array[i] = array[min_ind]
        array[min_ind] = tmp
    print('2.选择排序\n结果:{}, \n耗时:{}'.format(array, round(time.clock() - t1, 8)))
    return array


def insert_sort(array):
    t1 = time.clock()
    # 解法一
    for i in range(len(array)):
        insert_i = i
        for j in range(i - 1, -1, -1):
            if array[j] <= array[insert_i]:
                break
            else:
                tmp = array[insert_i]
                array[insert_i] = array[j]
                array[j] = tmp
                insert_i = j
    print('3.插入排序\n结果:{}, \n耗时:{}'.format(array, round(time.clock() - t1, 8)))
    return array


def insert_sort2(array):
    # 解法二
    t1 = time.clock()
    for i in range(len(array) - 1):
        pre_pointer = i
        curr_value = array[i + 1]
        while pre_pointer >= 0 and array[pre_pointer] > curr_value:
            array[pre_pointer + 1] = array[pre_pointer]
            pre_pointer -= 1
        array[pre_pointer + 1] = curr_value
    print('3.插入排序2\n结果:{}, \n耗时:{}'.format(array, round(time.clock() - t1, 8)))
    return array


def shell_sort(array):
    # 解法二
    t1 = time.clock()
    gap = len(array) // 2
    while gap > 0:
        for i in range(len(array) - gap):
            pre_pointer = i
            curr_value = array[i + gap]
            while pre_pointer >= 0 and array[pre_pointer] > curr_value:
                array[pre_pointer + gap] = array[pre_pointer]
                pre_pointer -= gap
            array[pre_pointer + gap] = curr_value
        gap = gap // 2
    print('4.希尔排序\n结果:{}, \n耗时:{}'.format(array, round(time.clock() - t1, 8)))
    return array


# 5.归并排序
def merge_sort(array):
    if len(array) < 2:
        return array
    mid = len(array) // 2
    left = array[: mid]
    right = array[mid:]
    return merge(merge_sort(left), merge_sort(right))


def merge(left, right):
    res = []
    ind_l, ind_r = 0, 0
    while ind_l < len(left) and ind_r < len(right):
        if left[ind_l] < right[ind_r]:
            res.append(left[ind_l])
            ind_l += 1
        else:
            res.append(right[ind_r])
            ind_r += 1
    if ind_l < len(left):
        res.extend(left[ind_l:])
    if ind_r < len(right):
        res.extend(right[ind_r:])
    return res


# 6.快速排序
def quick_sort(array):
    if len(array) < 2:
        return array
    ref = array[0]
    left = 1
    right = len(array) - 1
    while left < right:
        while array[left] <= ref:
            left += 1
        while array[right] > ref:
            right -= 1
        if left >= right:
            break
        else:
            tmp = array[left]
            array[left] = array[right]
            array[right] = tmp
    array[0] = array[left - 1]
    array[left - 1] = ref
    return quick_sort(array[0: left - 1]) + [ref] + quick_sort(array[left:])


# 7.计数排序
def count_sort(array):
    # 1.寻找最大最小值
    min_x = min(array)
    max_x = max(array)
    # 2.开辟长度为max_x-min_x+1的空间
    array_count = [0] * (max_x - min_x + 1)
    # 3.统计待排序元素出现的次数
    for i in array:
        array_count[i - min_x] += 1
    # 4.输出结果
    res_array = []
    for i, val in enumerate(array_count):
        while val > 0:
            res_array.append(i + min_x)
            val -= 1
    return res_array


# 7.计数排序优化稳定版
def count_sort2(array):
    # 1.寻找最大最小值
    min_x = min(array)
    max_x = max(array)
    # 2.开辟长度为max_x-min_x+1的空间
    array_count = [0] * (max_x - min_x + 1)
    # 3.统计待排序元素出现的次数
    for i in array:
        array_count[i - min_x] += 1
    # 4.累加数组
    for i in range(1, len(array_count)):
        array_count[i] = array_count[i] + array_count[i - 1]
    # 5.输出结果
    res_array = [0] * len(array)
    for i in range(len(array) - 1, -1, -1):
        res_array[array_count[array[i] - min_x] - 1] = array[i]
        array_count[array[i] - min_x] -= 1
    return res_array


# 8.桶排序
def bucket_sort(array):
    if not array:
        return []
    # 1.寻找最大值最小值
    min_x = min(array)
    max_x = max(array)
    dist = max_x - min_x
    # 2.开辟N个桶
    buckets = [[] for i in range(len(array))]
    # 3.遍历array,将数据依次入桶
    for val in array:
        num = int((val - min_x) * (len(array) - 1) / dist)
        buckets[num].append(val)
    res_array = []
    # 4.遍历桶,对每个桶分别排序,并输出
    for bucket in buckets:
        res_array.extend(sorted(bucket))
    return res_array


# 9.基数排序
def radix_sort(array):
    if not array:
        return []
    # 1.寻找最大的数字,确定位数
    max_x = max(array)
    digits = 0
    while max_x > 0:
        digits += 1
        max_x //= 10
    # 2.开辟10个桶
    buckets = [[], [], [], [], [], [], [], [], [], []]
    # 3.遍历最高位数,逐层入桶排序
    for i in range(digits):
        for val in array:
            tmp = val
            for k in range(i):
                tmp //= 10
            buckets[tmp % 10].append(val)
        array = []
        for j, val_list in enumerate(buckets):
            array.extend(val_list)
            buckets[j] = []
    return array


# 10.堆排序
class HeapSort:
    def __init__(self, array):
        self.array = array

    def min_heap_build(self):
        for ind in range(len(self.array) // 2 - 1, -1, -1):
            parent_ind = ind
            child_ind = 2 * parent_ind + 1
            tmp = self.array[parent_ind]
            while child_ind < len(self.array):
                if child_ind + 1 < len(self.array) and self.array[child_ind + 1] < self.array[child_ind]:
                    child_ind += 1
                if self.array[child_ind] > tmp:
                    break
                self.array[parent_ind] = self.array[child_ind]
                parent_ind = child_ind
                child_ind = 2 * child_ind + 1
            self.array[parent_ind] = tmp

    def min_heap_rebuild(self, parent_ind, length):
        child_ind = 2 * parent_ind + 1
        tmp = self.array[parent_ind]
        while child_ind < length:
            if child_ind + 1 < length and self.array[child_ind + 1] < self.array[child_ind]:
                child_ind += 1
            if self.array[child_ind] > tmp:
                break
            self.array[parent_ind] = self.array[child_ind]
            parent_ind = child_ind
            child_ind = 2 * child_ind + 1
        self.array[parent_ind] = tmp

    def max_heap_build(self):
        for ind in range(len(self.array) // 2 - 1, -1, -1):
            parent_ind = ind
            child_ind = 2 * parent_ind + 1
            tmp = self.array[parent_ind]
            while child_ind < len(self.array):
                if child_ind + 1 < len(self.array) and self.array[child_ind + 1] > self.array[child_ind]:
                    child_ind += 1
                if self.array[child_ind] < tmp:
                    break
                self.array[parent_ind] = self.array[child_ind]
                parent_ind = child_ind
                child_ind = 2 * child_ind + 1
            self.array[parent_ind] = tmp

    def max_heap_rebuild(self, parent_ind, length):
        child_ind = 2 * parent_ind + 1
        tmp = self.array[parent_ind]
        while child_ind < length:
            if child_ind + 1 < length and self.array[child_ind + 1] > self.array[child_ind]:
                child_ind += 1
            if self.array[child_ind] < tmp:
                break
            self.array[parent_ind] = self.array[child_ind]
            parent_ind = child_ind
            child_ind = 2 * child_ind + 1
        self.array[parent_ind] = tmp

    def sort(self):
        if not self.array:
            return []
        self.max_heap_build()
        for ind in range(len(self.array) - 1, 0, -1):
            tmp = self.array[ind]
            self.array[ind] = self.array[0]
            self.array[0] = tmp
            self.max_heap_rebuild(0, ind)
        return self.array


if __name__ == '__main__':
    array_test = [21, 33, 4, 2, 5, 23, 44, 8, 132, 64, 233, 632, 27, 1, 3, 34, 15, 19, 45, 51, 6]
    bubble_sort(array_test[:])
    select_sort(array_test[:])
    insert_sort(array_test[:])
    insert_sort2(array_test[:])
    shell_sort(array_test[:])
    t1 = time.clock()
    result = merge_sort(array_test[:])
    print('5.归并排序\n结果:{}, \n耗时:{}'.format(result, round(time.clock() - t1, 8)))
    t1 = time.clock()
    result = quick_sort(array_test[:])
    print('6.快速排序\n结果:{}, \n耗时:{}'.format(result, round(time.clock() - t1, 8)))
    t1 = time.clock()
    result = count_sort(array_test[:])
    print('7.计数排序\n结果:{}, \n耗时:{}'.format(result, round(time.clock() - t1, 8)))
    t1 = time.clock()
    result = count_sort2(array_test[:])
    print('7.计数排序优化稳定\n结果:{}, \n耗时:{}'.format(result, round(time.clock() - t1, 8)))
    t1 = time.clock()
    result = bucket_sort(array_test[:])
    print('8.桶排序\n结果:{}, \n耗时:{}'.format(result, round(time.clock() - t1, 8)))
    t1 = time.clock()
    result = radix_sort(array_test[:])
    print('9.基数排序\n结果:{}, \n耗时:{}'.format(result, round(time.clock() - t1, 8)))
    t1 = time.clock()
    result = HeapSort(array_test[:]).sort()
    print('10.堆排序\n结果:{}, \n耗时:{}'.format(result, round(time.clock() - t1, 8)))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值