1.用python实现快速排序
print quicksort([3,6,8,10,1,2,1])
# Prints "[1, 1, 2, 3, 6, 8, 10]"
'''
@author :Eric-chen
@contact:809512722@qq.com
@time :2017/12/24 23:49
@desc :write a method to realize print(quicksort([2,3,6,7,2,4,12,3]))
思路:不断的找中间的数,比中间小的放左边 相同的放中间 比中间大的放右边 然后递归
'''
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr)//2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right=[x for x in arr if x>pivot]
return quicksort(left)+quicksort(middle)+quicksort(right)
print(quicksort([1,12,5,4,12,3]))
遇到的问题:1.TypeError: list indices must be integers or slices, not float
答案:In Python 3.x, the / operator performs floating point division. If you want int division use // 在python3,x,/ 代表有小数点的商,如果想要整数的话,用//
2.RecursionError: maximum recursion depth exceeded in comparison
答案:quicksort(middle)middle中的数都是相等的,会无限次的循环下去的