#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);
少量数据的时候快速排序是快于插入排序的,但是快速排序性能的好坏直接跟枢轴的选择有关,枢轴选择的好的话排序会更快,如果枢轴选择不好的话就会拖慢排序的速度。