今天对四种基本的排序算法进行了简单的性能测试,测试代码如下:
#filename: test.py import time import random def quickSort(arr,l,r): if(l < r): i = l j = r x = arr[l] k = l while i < j: while i<j and arr[j]>x: j = j-1 if i < j: arr[k] = arr[j] k = j i = i+1 while i<j and arr[i]<x: i = i+1 if i < j: arr[k] = arr[i] k = i j = j-1 arr[k] = x quickSort(arr,l,k-1) quickSort(arr,k+1,r) def insertSort(arr,begin,end): i = begin+1 while i<=end: x = arr[i] k = i j = i-1 while j >= begin and arr[j]>x: arr[j+1]=arr[j] k = j j = j-1 arr[k]=x i = i+1 def bubbleSort(arr,begin,end): i=end while i>begin: j=begin while j<i: if arr[j]>arr[j+1]: arr[j],arr[j+1] = arr[j+1],arr[j] j = j+1 i = i-1 def selectSort(arr,begin,end): i=begin while i<end: j=i+1 while j<=end: if arr[i]>arr[j]: arr[i],arr[j] = arr[j],arr[i] j = j+1 i = i+1 arr = range(1,10000) funs = (quickSort,insertSort,bubbleSort,selectSort) for sort in funs: random.shuffle(arr) time1 = time.time() sort(arr,0,len(arr)-1) time2 = time.time() print time2-time1
为了保证测试结果的可靠性,进行了多次的测试,从上面的结果可以很明显的看出,快速排序>插入排序>选择排序>冒泡排序