关于排序算法效率的困惑

时间:2014-09-20 08:01:27

标签: python algorithm sorting

我已经阅读了关于选择/插入/ shell排序算法的书,并且根据本书,通常,选择排序比插入排序慢,这比shell排序慢。但是,我只使用Python运行了一些测试,发现选择排序是最快的!我无法弄清楚为什么,我能想到的唯一原因是列表元素之间的交换太多了。

这是我用于测试的代码:

import random
import time



lst = [ random.randint(1,10000) for _ in xrange(10000) ]

def timeit(f):
    def wrapper(*args):
        t1 = time.time()
        result = f(*args)
        t2 = time.time()
        print 'time: %f' %(t2 - t1) 
        return result
    return wrapper

@timeit
def selectionSort(lst):
    for i in xrange(len(lst)):
        minNum = lst[i]
        for j in xrange(i+1, len(lst)):
            if lst[j] < minNum:
                minNum = lst[j]
        lst[i], minNum = minNum, lst[i]
    return lst

@timeit
def insertionSort(lst):
    for i in xrange(len(lst)):
        for j in xrange(i, 0, -1):
            if lst[j] < lst[j-1]:
                lst[j], lst[j-1] = lst[j-1], lst[j]
            else:
                break
    return lst

@timeit
def shellSort(lst):
    h = 1
    while (h < len(lst)//3):
        h = h * 3 + 1


    while (h >= 1):
        for i in xrange(h, len(lst)):
            for j in xrange(i, h-1, -h):  
                if lst[j] < lst[j-h]:
                    lst[j], lst[j-h] = lst[j-h], lst[j]
                else:
                    break
        h //= 3
    return lst


selectionSort(lst[:])
insertionSort(lst[:])
shellSort(lst[:])

我机器上的结果如下:

[linuxfish@Arch week2]$./sortAlgorithms.py 
time: 4.533489
time: 22.247762
time: 12.867564

这是我添加了两行代码后的结果,非常了不起......

time: 4.937693
time: 16.773167
time: 0.179526

排序方法改编自Robert Sedgewick的this book,我认为我实现的算法与本书的内容完全相同,尽管本书中的原始算法是用Java编写的

1 个答案:

答案 0 :(得分:0)

查看http://bigocheatsheet.com/排序部分。和http://en.wikipedia.org/wiki/Shellsort您使用的数据似乎会导致不同的行为,因为只有选择排序是稳定的。

这是一个信息:

               | Best   |  Average | Worst
Select Sort    | O(n^2) | O(n^2)   |  O(n^2)

Insertion Sort | O(n)   | O(n^2)   | O(n^2)

Shell sort     | O(nlogn) | depends on the gap | O(n^2)
相关问题