1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # @Time : 2019/9/15 下午5:06 4 # @Author : lb 5 # @File : sort.py 6 # @Desc : 7 import numpy as np 8 arr = list(np.random.randint(20, size=10)) 9 #arr = [1, 11, 1, 2, 43, 11] 10 def buble_sort(a): 11 """ 12 冒泡排序: 两两比较,每次循环都找到最大的一个放到最右侧 13 :param a: 14 :return: 15 """ 16 if len(a) < 2: 17 return a 18 for i in xrange(len(a)): 19 for j in xrange(len(a)-i-1): 20 if a[j] > a[j+1]: 21 a[j], a[j+1] = a[j+1], a[j] 22 return a 23 24 25 def sel_sort(a): 26 """ 27 选择排序:每次循环都找到剩余的元素中最大的一个,与当前外层循环的位置进行交换 28 :param a: 29 :return: 30 """ 31 if len(a) < 2: 32 return a 33 for i in xrange(len(a)-1): 34 tmp = a[i] 35 pos = i 36 for j in xrange(i+1, len(a)): 37 if a[j] < tmp: 38 tmp = a[j] 39 pos = j 40 a[i], a[pos] = a[pos], a[i] 41 return a 42 43 44 def ins_sort(a): 45 """ 46 插入排序:每次对已经排好的有序数列进行轮训,如果大于监哨,则当前的元素右移n(直接排序时:n=1, 希尔排序时:n=gap)个单位 47 :param a: 48 :return: 49 """ 50 if len(a) < 2: 51 return a 52 for i in xrange(1, len(a)): 53 tmp = a[i] 54 j = i 55 while j - 1 >= 0 and a[j-1] > tmp: 56 a[j] = a[j-1] 57 j -= 1 58 a[j] = tmp 59 60 return a 61 62 63 def shell_sort(a): 64 """ 65 希尔排序,改进的插入排序,一次移动gap个元素 66 :param a: 67 :return: 68 """ 69 if len(a) < 2: 70 return a 71 gap = len(a) // 2 72 while gap > 0: 73 for i in xrange(gap, len(a)): 74 tmp = a[i] 75 j = i 76 while j >= gap and a[j-gap] > tmp: 77 a[j] = a[j-gap] 78 j -= gap 79 a[j] = tmp 80 gap //= 2 81 return a 82 83 def quick_sort(a): 84 """ 85 快速排序:分治原则,设置标准值mid,小于mid的放左侧,大于mid的放右侧,递归实现 86 :param a: 87 :return: 88 """ 89 if len(a) < 2: 90 return a 91 L, R = [], [] 92 mid = a[len(a) // 2] 93 a.remove(mid) 94 for i in a: 95 if i > mid: 96 R.append(i) 97 else: 98 L.append(i) 99 return quick_sort(L) + [mid] + quick_sort(R) 100 101 102 def merge_sort(a): 103 """ 104 归并排序,分治原则,将一路归并逐渐抽象到二路归并 105 :param arr: 106 :return: 107 """ 108 def two_merge(L,R): 109 index_L = index_R = 0 110 ret = [] 111 while index_L < len(L) and index_R < len(R): 112 if L[index_L] < R[index_R]: 113 ret.append(L[index_L]) 114 index_L += 1 115 else: 116 ret.append(R[index_R]) 117 index_R += 1 118 if index_L == len(L): 119 ret.extend(R[index_R:]) 120 else: 121 ret.extend(L[index_L:]) 122 return ret 123 if len(a) < 2: 124 return a 125 mid = len(a) // 2 126 L = merge_sort(a[:mid]) 127 R = merge_sort(a[mid:]) 128 return two_merge(L, R)