Python 中一行代码搞定快排
QuickSort = lambda X: [] if len(X) == 0 else QuickSort([i for i in X if i < X[0]]) + [X[0]] + QuickSort([i for i in X if i > X[0]])
Python 快速排序
def quick_sort(arr):
if len(arr) <= 1:
return arr
mark = arr[random.randint(0, len(arr) - 1)]
low_part = []
mid_part = []
hih_part = []
for x in arr:
if x < mark:
low_part.append(x)
if x == mark:
mid_part.append(x)
if x > mark:
hih_part.append(x)
low_part = quick_sort(low_part)
hih_part = quick_sort(hih_part)
res = low_part + mid_part + hih_part
return res
Golang 快速排序
func QuickSort(s []int) []int {
if len(s) <= 1{
return s
}
mark := s[rand.Intn(len(s))]
var lowPart []int
var midPart []int
var hihPart []int
for _, x :=range s{
switch {
case x < mark:
lowPart = append(lowPart, x)
case x == mark:
midPart = append(midPart, x)
case x > mark:
hihPart = append(hihPart, x)
}
}
lowPart = QuickSort(lowPart)
hihPart = QuickSort(hihPart)
var res []int
res = append(lowPart, midPart...)
res = append(res, hihPart...)
return res
}