题目标题

写出快速排序法

难度:初级

数据分析
参考解析

def partition(arr,low,high):
i = ( low-1 ) # 最小元素索引
pivot = arr[high]

  1. for j in range(low , high):
  2. # 当前元素小于或等于 pivot
  3. if arr[j] <= pivot:
  4. i = i+1
  5. arr[i],arr[j] = arr[j],arr[i]
  6. arr[i+1],arr[high] = arr[high],arr[i+1]
  7. return ( i+1 )

arr[] —> 排序数组

low —> 起始索引

high —> 结束索引

快速排序函数

def quickSort(arr,low,high):
if low < high:

  1. pi = partition(arr,low,high)
  2. quickSort(arr, low, pi-1)
  3. quickSort(arr, pi+1, high)

arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quickSort(arr,0,n-1)
print (“排序后的数组:”)
for i in range(n):
print (“%d” %arr[i])