---
title: "Python排序算法 - 菜鸟学Python（2）  ,Python"
author: "ay_guobo"
date: "2011-10-21T13:01:00Z"
tags: []
categories: ["编程语言"]
slug: "python-python-2-python"
draft: false
lastmod: "2011-10-21T13:01:00Z"
id: 1206560
url: "https://GUOBO.iteye.com/blog/1206560"
---

\# timing 7 different Python sorting algorithms with a list of integers  
\# each function is given the same list (fresh copy each time)  
\# tested with Python2.7  

\# -\*- coding: utf-8 -\*-

 

"""

Created on Tue Oct 18 09:54:20 2011

 

@author: Guo

"""

    

import random  # for generating random numbers  
import time    # for timing each sort function with time.clock()

DEBUG = False  # set True to check results of each sort

N = 1000     # number of elements in list  
list1 = \[]   # list of integer elements

for i in range(0, N):  
    list1.append(random.randint(0, N-1))

#print list1  # test

def print\_timing(func):  
    def wrapper(\*arg):  
        t1 = time.clock()  
        res = func(\*arg)  
        t2 = time.clock()  
        print '%s took %0.3fms' % (func.func\_name, (t2-t1)\*1000.0)  
        return res  
    return wrapper

\# declare the @ decorator just above each sort function, invokes print\_timing()  
@print\_timing  
def adaptive\_merge\_sort(list2):  
    """adaptive merge sort, built into Python since version 2.3"""  
    list2.sort()

@print\_timing  
def bubble\_sort(list2):  
    #swap\_test = False  
    for i in range(0, len(list2) - 1):  
        # as suggested by kubrick, makes sense  
        swap\_test = False  
        for j in range(0, len(list2) - i - 1):  
            if list2\[j] &gt; list2\[j + 1]:  
                list2\[j], list2\[j + 1] = list2\[j + 1], list2\[j]  # swap  
            swap\_test = True  
        if swap\_test == False:  
            break

\# selection sort  
@print\_timing  
def selection\_sort(list2):  
    for i in range(0, len (list2)):  
        min = i  
        for j in range(i + 1, len(list2)):  
            if list2\[j] &lt; list2\[min]:  
                min = j  
        list2\[i], list2\[min] = list2\[min], list2\[i]  # swap  
        
\# insertion sort  
@print\_timing  
def insertion\_sort(list2):  
    for i in range(1, len(list2)):  
        save = list2\[i]  
        j = i  
        while j &gt; 0 and list2\[j - 1] &gt; save:  
            list2\[j] = list2\[j - 1]  
            j -= 1  
        list2\[j] = save  
    
\# quick sort  
@print\_timing  
def quick\_sort(list2):  
    quick\_sort\_r(list2, 0, len(list2) - 1)

\# quick\_sort\_r, recursive (used by quick\_sort)  
def quick\_sort\_r(list2 , first, last):  
    if last &gt; first:  
        pivot = partition(list2, first, last)  
        quick\_sort\_r(list2, first, pivot - 1)  
        quick\_sort\_r(list2, pivot + 1, last)

\# partition (used by quick\_sort\_r)  
def partition(list2, first, last):  
    sred = (first + last)/2  
    if list2\[first] &gt; list2 \[sred]:  
        list2\[first], list2\[sred] = list2\[sred], list2\[first]  # swap  
    if list2\[first] &gt; list2 \[last]:  
        list2\[first], list2\[last] = list2\[last], list2\[first]  # swap  
    if list2\[sred] &gt; list2\[last]:  
        list2\[sred], list2\[last] = list2\[last], list2\[sred]    # swap  
    list2 \[sred], list2 \[first] = list2\[first], list2\[sred]    # swap  
    pivot = first  
    i = first + 1  
    j = last  
    
    while True:  
        while i &lt;= last and list2\[i] &lt;= list2\[pivot]:  
            i += 1  
        while j &gt;= first and list2\[j] &gt; list2\[pivot]:  
            j -= 1  
        if i &gt;= j:  
            break  
        else:  
            list2\[i], list2\[j] = list2\[j], list2\[i]  # swap  
    list2\[j], list2\[pivot] = list2\[pivot], list2\[j]  # swap  
    return j

\# heap sort  
@print\_timing  
def heap\_sort(list2):  
    first = 0  
    last = len(list2) - 1  
    create\_heap(list2, first, last)  
    for i in range(last, first, -1):  
        list2\[i], list2\[first] = list2\[first], list2\[i]  # swap  
        establish\_heap\_property (list2, first, i - 1)

\# create heap (used by heap\_sort)  
def create\_heap(list2, first, last):  
    i = last/2  
    while i &gt;= first:  
        establish\_heap\_property(list2, i, last)  
        i -= 1

\# establish heap property (used by create\_heap)  
def establish\_heap\_property(list2, first, last):  
    while 2 * first + 1 &lt;= last:  
        k = 2 * first + 1  
        if k &lt; last and list2\[k] &lt; list2\[k + 1]:  
            k += 1  
        if list2\[first] &gt;= list2\[k]:  
            break  
        list2\[first], list2\[k] = list2\[k], list2\[first]  # swap  
        first = k

\# merge sort  
@print\_timing  
def merge\_sort(list2):  
    merge\_sort\_r(list2, 0, len(list2) -1)

\# merge sort recursive (used by merge\_sort)  
def merge\_sort\_r(list2, first, last):  
    if first &lt; last:  
        sred = (first + last)/2  
        merge\_sort\_r(list2, first, sred)  
        merge\_sort\_r(list2, sred + 1, last)  
        merge(list2, first, last, sred)

\# merge (used by merge\_sort\_r)  
def merge(list2, first, last, sred):  
    helper\_list = \[]  
    i = first  
    j = sred + 1  
    while i &lt;= sred and j &lt;= last:  
        if list2 \[i] &lt;= list2 \[j]:  
            helper\_list.append(list2\[i])  
            i += 1  
        else:  
            helper\_list.append(list2 \[j])  
            j += 1  
    while i &lt;= sred:  
        helper\_list.append(list2\[i])  
        i +=1  
    while j &lt;= last:  
        helper\_list.append(list2\[j])  
        j += 1  
    for k in range(0, last - first + 1):  
        list2\[first + k] = helper\_list \[k]

\# test sorted list by printing the first 10 elements  
def print10(list2):  
    for k in range(10):  
        print list2\[k],  
    print

\# run test if script is executed  
if \_\_name\__ == "\_\_main\_\_" :  
    print "timing 7 sorting algorithms with a list of 1000 integers:"  
    # make a true copy of list1 each time  
    list2 = list(list1)  
    adaptive\_merge\_sort(list2)  
    if DEBUG:  
        print10(list2)  
    list2 = list(list1)  
    bubble\_sort(list2)  
    if DEBUG:  
        print10(list2)  
    list2 = list(list1)  
    heap\_sort(list2)  
    if DEBUG:  
        print10(list2)  
    list2 = list(list1)  
    insertion\_sort(list2)  
    if DEBUG:  
        print10(list2)  
    list2 = list(list1)  
    merge\_sort(list2)  
    if DEBUG:  
        print10(list2)  
    list2 = list(list1)  
    quick\_sort(list2)  
    if DEBUG:  
        print10(list2)  
    list2 = list(list1)  
    selection\_sort(list2)  
    if DEBUG:  
        print10(list2)  
    # final test  
    list2 = list(list1)  
    if DEBUG:  
        print "final test: ",  
        print10(list2)

    #raw\_input( "Press Enter to continue..." )

"""  
typical results:  
timing 7 sorting algorithms with a list of 1000 integers:  
adaptive\_merge\_sort took 0.560ms  
bubble\_sort took 269.691ms  
heap\_sort took 13.556ms  
insertion\_sort took 130.870ms  
merge\_sort took 19.272ms  
quick\_sort took 6.849ms  
selection\_sort took 120.291ms

\`````````````````````````````

timing 7 sorting algorithms with a list of 1000 integers:

adaptive\_merge\_sort took 0.470ms

bubble\_sort took 242.426ms

heap\_sort took 10.453ms

insertion\_sort took 112.837ms

merge\_sort took 11.294ms

quick\_sort took 6.688ms

selection\_sort took 124.995ms

"""