首頁  >  文章  >  後端開發  >  python演算法

python演算法

高洛峰
高洛峰原創
2016-10-19 17:20:551068瀏覽

插入排序的基本概念:有一個已經有序的資料序列,要求在這個已經排好的資料序列中插入一個數,但要求插入後此資料序列仍然有序,這個時候就要用到一種新的排序方法-插入排序法,插入排序的基本操作就是將一個資料插入到已經排好序的有序資料中,從而得到一個新的、個數加一的有序數據,演算法適用於少量數據的排序,時間複雜度為O(n^2)。是穩定的排序方法。插入演算法將要排序的陣列分成兩部分:第一部分包含了這個陣列的所有元素,但將最後一個元素除外,而第二部分只包含這一個元素。在第一部分排序後,再把這個最後元素插入到此刻已是有序的第一部分裡的位置

# -*- encoding: utf-8 -*-
  
def insertion_sort(iterable, cmp=cmp):
    """插入排序,伪码如下:
    INSERTION-SORT(A)
    1  for j ← 2 to length[A] // 从第二个数开始
    2    do key ← A[j] // 该数作为待排序的数
    3      ▷ Insert A[j] into the sorted sequence A[1..j-1]. // 将key插入已排序子数组
    4      i ← j-1 // key前一位索引
    5      while i > 0 and A[i] > key // 前一位存在且大于key时
    6        do A[i+1] ← A[i] // 后移一位
    7           i ← i-1 // 索引再向前一位
    8      A[i+1] ← key // 直到前一位不存在或<=key了,key插入
  
    T(n) = θ(n^2)
  
    Args:
        iterable (Iterator): 可迭代对象。
        cmp (Function): 比较函数。默认为内建函数cmp()。
  
    Returns:
        一个排序后的列表。
    """
    if (iterable == None):
        return None
    lst = [] # 结果列表
    length = len(iterable)
  
    for key in iterable:
        i = len(lst) # 列表长度
        # 从末尾往前与key比较,直到不大于key
        while i > 0 and cmp(lst[i-1], key) > 0:
            i = i - 1
        lst.insert(i, key); # i处插入key
  
    return lst
  
if __name__ == &#39;__main__&#39;:
    import random, timeit
  
    items = range(10000)
    random.shuffle(items)
  
    def test_sorted():
        print(items)
        sorted_items = sorted(items)
        print(sorted_items)
  
    def test_insertion_sort():
        print(items)
        sorted_items = insertion_sort(items)
        print(sorted_items)
  
    test_methods = [test_sorted, test_insertion_sort]
    for test in test_methods:
        name = test.__name__ # test.func_name
        t = timeit.Timer(name + &#39;()&#39;, &#39;from __main__ import &#39; + name)
        print(name + &#39; takes time : %f&#39; % t.timeit(1))


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn