排序算法与查找算法
排序算法
冒泡排序
- 时间复杂度:O(n²)
- 空间复杂度:O(1)
- 健壮性:健壮
- 难易程度:简单
def bubbleSort(li): for i in range(len(li) - 1): for j in range(len(li) - i - 1): if li[j] > li[j + 1]: li[j], li[j + 1] = li[j + 1], li[j] li = [345, 456, 68.435, 1, 6, 4, 568, ] bubbleSort(li) print(li)
选择排序
- 时间复杂度:O(n²)
- 空间复杂度:O(1)
- 健壮性:健壮
- 难易程度:简单
def selectSort(li): for i in range(len(li) - 1): min = I # 选择一个小的来比较 for j in range(i + 1, len(li)): if li[min] > li[j]: li[min], li[j] = li[j], li[min] li = [345, 456, 68.435, 1, 6, 4, 568, ] selectSort(li) print(li)
插入排序
- 时间复杂度:O(n²)
- 空间复杂度:O(1)
- 健壮性:健壮
- 难易程度:较复杂
def insertSort(li): for i in range(len(li) - 1): temp = li[i] j = i - 1 while j >= 0 and li[j] > temp: li[j + 1] = li[j] j = j - 1 li[j + 1] = temp li = [345, 456, 68.435, 1, 6, 4, 568, ] insertSort(li) print(li)
快速排序
- 时间复杂度:O(nlogn)
- 空间复杂度:O(nlogn)
- 健壮性:不稳定
- 难易程度:复杂
# 二分左右
def partition(list_for_partition, left, right):
# 中轴点
pivot = list_for_partition[left]
while left < right:
while left < right and list_for_partition[right] >= pivot:
right -= 1
list_for_partition[left] = list_for_partition[right]
while left < right and list_for_partition[left] <= pivot:
left += 1
list_for_partition[right] = list_for_partition[left]
list_for_partition[left] = pivot
return left
# 快速排序
def sort_quickly(list_for_partition, left, right):
if left < right:
pivot = partition(list_for_partition, left, right)
sort_quickly(list_for_partition, left, pivot - 1)
sort_quickly(list_for_partition, pivot + 1, right)
return list_for_partition
# 输出结果
def output_sort_result(list_for_partition):
return sort_quickly(list_for_partition, 0, len(list_for_partition) - 1)
堆排序
- 时间复杂度:O(nlog₂n)
- 空间复杂度:O(1)
- 健壮性:不稳定
- 难易程度: 困难
def heap_sort(array): def heap_adjust(parent): child = 2 * parent + 1 # left child while child < len(heap): if child + 1 < len(heap): if heap[child + 1] > heap[child]: child += 1 # right child if heap[parent] >= heap[child]: break heap[parent], heap[child] = \ heap[child], heap[parent] parent, child = child, 2 * child + 1 heap, array = array.copy(), [] for i in range(len(heap) // 2, -1, -1): heap_adjust(i) while len(heap) != 0: heap[0], heap[-1] = heap[-1], heap[0] array.insert(0, heap.pop()) heap_adjust(0) return array
查找算法
顺序查找
二分查找
原创作者:马一特
文章出处:http://www.cnblogs.com/mayite/
版权声明:自由转载-非商用-非衍生-保持署名
(创意共享4.0许可证)
转载说明:如果文章对您有帮助,欢迎点赞,评论加转载,赠人玫瑰,手留余香