排序算法

时间复杂度

二分法

def bin_search(data_set, value):
    low = 0
    high = len(data_set) - 1
    while low <= high:
        mid = (low + high) // 2
        if data_set[mid] == value:
            return mid
        elif data_set[mid] > value:
            high = mid - 1
        else:
            low = mid + 1

 

冒泡排序

def Bubble_sort(li):
    for i in range(len(li) - 1):
        for j in range(len(li) - 1 - i):
            if li[j] > li[j + 1]:
                li[j], li[j + 1] = li[j + 1], li[j]

代码关键点:

  • 无序区

def bubble_sort_1(li):
    for i in range(len(li) - 1):
        exchange = False
        for j in range(len(li) - i - 1):
            if li[j] > li[j + 1]:
                li[j], li[j + 1] = li[j + 1], li[j]
                exchange = True
            if not exchange:
                return

选择排序

def select_sort(li):
    for i in range(len(li)):
        minLoc = i  ###i = 0
        for j in range(i + 1, len(li)):
            if li[j] < li[minLoc]:
                li[j], li[minLoc] = li[minLoc], li[j]

代码关键点:

  • 无序区
  • 最小数的位置

插入排序

 

def insert_sort(li):
    for i in range(1, len(li)):
        tmp = li[i]
        j = i - 1
        while j >= 0 and li[j] > tmp:
            li[j + 1] = li[j]
            j = j - 1
        li[j + 1] = tmp

快速排序

 

def partition(li, left, right):
    tmp = li[left]
    while left < right:
        while left < right and li[right] >= tmp:
            right = right - 1
        li[left] = li[right]
        while left < right and li[left] <= tmp:
            left = left + 1
        li[right] = li[left]
    li[left] = tmp
    return left

def quick_sort(li, left, right):
    if left < right:
        mid = partition(li, left, right)
        quick_sort(li, left, mid - 1)
        quick_sort(li, mid + 1, right)

 

import time, random

li = [random.randint(1, 100) for _ in range(100000)]
start = time.time()
quick_sort(li, 0, len(li) - 1)
cost = time.time() - start
print('quick_sort:%s' % (cost))
posted @ 2019-12-24 16:40  waller  阅读(128)  评论(0编辑  收藏  举报