quicksort--python--others
来源:互联网 发布:信捷plc编程案例 编辑:程序博客网 时间:2024/06/11 06:53
搜了stackoverflow 上的quicksort, 明白了什么叫elegant, compact code:
def qsort(arr): if len(arr) <= 1: return arr else: return qsort([x for x in arr[1:] if x<arr[0]]) + [arr[0]] + qsort([x for x in arr[1:] if x>=arr[0]])
Or you can make this a little bit longer to make sense:
def sort(array=[12,4,5,6,7,3,1,15]): less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: greater.append(x) # Don't forget to return something! return sort(less)+ equal +sort(greater) # Just use the + operator to join lists # Note that you want equal ^^^^^ not pivot else: # You need to hande the part at the end of the recursion - when you only have one element in your array, just return the array. return array
or this version:
def sort(A): if len(A) <= 1: return A else: pivot = A[0] small = [] mid = [] big = [] for item in A: if item == pivot: mid.append(item) elif item > pivot: big.append(item) else: small.append(item) small = sort(small) mid = mid #不能递归sort(mid),否则当有重复元素时,会死循环 big = sort(big) A = small + mid + big return AA = [10,10,11,52,3,8,4,-1]print Aprint sort(A)
0 0
- quicksort--python--others
- Python 8 Others
- python quickSort
- quicksort(python)
- others
- others
- Others
- others
- Others
- python get local ip and sth. others
- python 版 quicksort 快排
- Quicksort
- QuickSort
- quicksort
- quicksort
- QuickSort
- QuickSort
- QuickSort
- akoj-1211-统计数字
- sicily 1093
- 树莓派平台4位共阴数码管Python编程
- 使用skyeye运行uboot, linux-2.6.31和busybox
- 向左对齐的Gallery
- quicksort--python--others
- java 集合总览
- 最长的无重复字符的字符串 longest substring with no repeating characters
- Hadoop即将过时了吗?
- Unity MeshBaker 合并网格和材质
- When Linux Runs Out of Memory
- Java webp转jpg
- 第13周项目--数组大折腾3
- restful基于SpringMVC的实现(上)