快速排序
快速排序python代码:
1 def partPos( arr , left , right ): 2 #选取中间的mid为分隔数值 3 mid = (left+right)//2 4 #将其与arr[right]交换 5 arr[mid],arr[right] = arr[right],arr[mid] 6 pivot = arr[right] 7 i = left 8 for j in range(left,right+1): 9 if arr[j]<=pivot: 10 arr[i],arr[j] = arr[j],arr[i] 11 i += 1 12 return i-1 13 14 def quickSort( arr , left , right ): 15 if left<right: 16 #获取此次分隔后中间数值位置 17 pos = partPos( arr , left , right ) 18 #新一轮分隔 19 quickSort( arr , left , pos-1 ) 20 quickSort( arr , pos+1 , right ) 21 return 22 23 nums = [9,8,7,6,5,4,3,2,1] 24 quickSort(nums,0,8) 25 print(nums)
输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]