生成随机数列
1 | from random import randint |
生成基本有序的数列
1 | def generateNearlyOrderedArray(n=10, swapTimes=2): |
测试算法性能
1 | from timeit import Timer |
冒泡排序
1 | def bubbleSort(nums): |
上面这个是向后冒泡,还有个向前冒泡的版本:(可以由i判断向哪冒泡)
1 | def bubbleSort(nums): |
选择排序
1 | def selectionSort(nums): |
插入排序
1 | def insertionSort(nums): |
快速排序
1 | def quickSort(nums,l,r): # 闭区间[l,r] |
归并排序
1 | tmp=[0]*n |
中间部分可以这样记忆(虽然不可以这样运行)
1 | k,i,j=0,l,mid+1 # 分成两部分,[l,mid],[mid+1,r] |
希尔排序
1 | def shellSort(nums): |
为什么python不支持自增(i++)?
《learning python》这样解释:
although Python now supports statements like X += Y, it still does not have C’s auto-increment/decrement operators (e.g., X++, −−X). These don’t quite map to the Python object model because Python has no notion of in-place changes to immutable objects like numbers.