1. 程式人生 > >python 快速排序和插入排序比較

python 快速排序和插入排序比較

#coding=utf-8
#插入排序
import time
testArr = [5,3,2,7,8,0,22,32,-1];
arrLen = testArr.__len__();
def insertSort(arr):
    for num in range(1,arrLen):
        #比較的標準
        stand = arr[num];
        for innerNum in range(num-1,-1,-1):
            print("stand is ",stand);
            if arr[innerNum] > stand:
                temp = arr[innerNum];
                arr[innerNum] = arr[innerNum+1];
                arr[innerNum + 1] = temp;
                print("testArr is ",testArr);
            else:
                break;
start = int(round(time.time() * 1000));
insertSort(testArr);
end = int(round(time.time() * 1000));
print("insert sort cost ",end-start,'ms');
#快速排序
testArr = [5,3,2,7,8,0,22,32,-1];
def quickSort(array,left,right):
    if left < array.__len__():
        #樞軸的值
        main = array[left];
        i = left;
        j = right;
        if(j < i):
            return;
        while i != j:
            while i < j and (array[j] >= main):
                j = j - 1;
            if(j > i):
                array[i] = array[j];
            while i < j and (array[i] <= main):
                i = i + 1;
            if(j > i):
                array[j] = array[i];
        array[i] = main;
        quickSort(array,left,i-1);
        quickSort(array,i+1,right);
print("testArr's length is ",testArr.__len__() - 1);
start = int(round(time.time() * 1000))
quickSort(testArr,0,testArr.__len__()-1);
end = int(round(time.time() * 1000))
print("quick sort cost ",end - start);
print("testArr is ",testArr);

少量資料的時候快速排序是快於插入排序的,但是快速排序效能的好壞直接跟樞軸的選擇有關,樞軸選擇的好的話排序會更快,如果樞軸選擇不好的話就會拖慢排序的速度。