import random
import time
defPartition(A, low, high):
x = A[low]
i = low +1
j = high
while(i < j):while(A[i]<= x and i < high):
i +=1while(A[j]> x and j > low):
j -=1if(i < j):
temp = A[i]
A[i]= A[j]
A[j]= temp
i +=1
j -=1
A[low]= A[j]
A[j]= x
return j
defQuiteSort(A, low, high):if(high > low):
m = Partition(A, low, high)
QuiteSort(A, low, m -1)
QuiteSort(A, m +1, high)return A
if __name__ =='__main__':
a =[]for i inrange(1000000):#生成随机list
a.append(random.randint(1,100000000))print(a)
t1 = time.time()print(QuiteSort(a,0,len(a)-1))print("Quitesort用时:",time.time()- t1,"秒")#排序时间分析
归并排序的递归实现
import random
import time
defmerge(a, b):
i =0
j =0
c =[]
total =len(a)+len(b)while(len(c)!= total):if(i ==len(a)):for x inrange(len(b)- j):
c.append(b[j])
j +=1breakif(j ==len(b)):for x inrange(len(a)- i):
c.append(a[i])
i +=1breakif(a[i]<= b[j]):
c.append(a[i])
i +=1else:
c.append(b[j])
j +=1return c
defMergeSort(array):
len_a =len(array)
temp_low =[]
temp_high =[]if len_a >1:
n =0for elems in array:if n <(len_a -1)/2:
temp_low.append(elems)else:
temp_high.append(elems)
n +=1
temp_low1 = MergeSort(temp_low)
temp_high1 = MergeSort(temp_high)return merge(temp_low1, temp_high1)if len_a ==1:return array
if __name__ =='__main__':
a =[]for i inrange(1000000):
a.append(random.randint(1,100000000))print(a)
t1 = time.time()print(MergeSort(a))
t2 = time.time()print("用时: ", t2 - t1,"秒")
快速排序的递归实现方式import randomimport timedef Partition(A, low, high): x = A[low] i = low + 1 j = high while (i < j): while (A[i] <= x and i < high): i += 1 while (A[j] > x and j > low):