Python 6种排序方法源码及其对比图

本次对于1000行数据用6种排序方法进行排序

6种排序算法如下:

  1. 插入排序(insertion sort)
  2. 冒泡排序(bubble sort)
  3. 归并排序(merge sort)
  4. Tim排序(Tim’s sort)
  5. 快速排序(quick sort)
  6. 计数排序(counting sort)

数据生成源码:

import random

file = open("test_data.txt", "w")


for j in range(2, 1002):
    array = [random.randint(1, 1000) for i in range(1, j)]
    random.shuffle(array)
    string = str(array[0])
    for index in range(1, j - 1):
        string += " "
        string += str(array[index])
    string += "\n"
    file.write(string)

file.close()

部分测试数据截图:
测试数据前20行

插入排序(insertion sort)代码

import time


time_file = open("insertion_time.txt", "w")
number_file = open("test_data.txt", "r")


def teacher_insertion_sort(arr):
    start_time = time.process_time_ns()
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and key < arr[i]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    end_time = time.process_time_ns()

    return end_time - start_time


while True:
    test_array = (number_file.readline())[:-1].split(" ")
    if test_array != [""]:

        time_file.write(str(teacher_insertion_sort(test_array)))
        time_file.write("\n")
    else:
        break

冒泡排序(bubble sort)代码

import time


def bubble_sort(arr):
    start_time = time.process_time_ns()
    n = len(arr)
    swapped = False

    for i in range(n - 1):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                swapped = True
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

        if not swapped:
            end_time = time.process_time_ns()
            return end_time - start_time

    end_time = time.process_time_ns()
    return end_time - start_time


time_file = open("bubble_time.txt", "w")
number_file = open("test_data.txt", "r")


while True:
    test_array = (number_file.readline())[
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值