这是Randomized Quicksort的正确实现吗?

时间:2018-06-10 15:24:40

标签: python algorithm sorting data-structures

#Randomized Quick Sort
import random
def partition(array , low , high):
   i = low - 1
   pivot = array[high]

   for j in range( low , high):

       if array[j] <= pivot:

           i += 1
           array[i],array[j] = array[j],array[i] # Swapping 

   arr[i+1],arr[high] = arr[high],arr[i+1] 
   return(i+1)
def QuickSort(array,low,high):

   if low < high:
       random_value = random.randint(low,high)
       array[random_value] , array[high] = array[high], array[random_value] 
       mid = partition(array,low,high)
       QuickSort(array,low,mid-1)
       QuickSort(array,mid+1,high)

arr = [1,2,3,4,5,6,7,8,9,10]
n = len(arr)
QuickSort(arr,0,n-1)
print ("Sorted array is:")
for i in range(n):
   print (arr[i])

我已经用python实现了随机快速排序算法。但我不确定它是否正确。另外,有没有什么方法可以检查两者的时间复杂度,正常的快速排序和一些数据集的随机快速排序?

三江源

0 个答案:

没有答案