|
| 1 | +''' |
| 2 | + 线性查找 |
| 3 | + 冒泡排序 |
| 4 | + 选择排序 |
| 5 | + 插入排序 |
| 6 | + 希尔排序 |
| 7 | +''' |
| 8 | +import random |
| 9 | +import time |
| 10 | +# 线性查找算法 |
| 11 | +def liner_search(list,value): |
| 12 | + for item in range(len(list)): |
| 13 | + if(list[item] == value): |
| 14 | + return item; |
| 15 | + return -1; |
| 16 | +print("---------------------线性查找"); |
| 17 | +testList = [1,2,3,4,5,6,7,8,9] |
| 18 | +start = time.perf_counter() |
| 19 | +print(liner_search(testList, 8)) |
| 20 | +end = time.perf_counter() |
| 21 | +print("时间:", end-start) |
| 22 | + |
| 23 | +# 选择排序 |
| 24 | +def selectionSort(sortList): |
| 25 | + for i in range(len(sortList)): |
| 26 | + minIndex = i ; |
| 27 | + for j in range(i,len(sortList)): |
| 28 | + if sortList[minIndex]>sortList[j]: |
| 29 | + minIndex=j |
| 30 | + sortList[i],sortList[minIndex] = sortList[minIndex],sortList[i] |
| 31 | + return sortList |
| 32 | + |
| 33 | + |
| 34 | + # 冒泡排序 |
| 35 | +def bubble_sort(sortList): |
| 36 | + for i in range(len(sortList)): |
| 37 | + isSwap = False; #设置标志位,若已排序好,则不排序 |
| 38 | + for j in range(len(sortList)-i-1): |
| 39 | + if sortList[j] > sortList[j + 1]: |
| 40 | + sortList[j], sortList[j + 1] = sortList[j + 1], sortList[j] |
| 41 | + isSwap = True |
| 42 | + if not isSwap: |
| 43 | + break |
| 44 | + |
| 45 | +# 插入排序 |
| 46 | +def insertionSort(sortList): |
| 47 | + for i in range(1,len(sortList)): |
| 48 | + currentValue = sortList[i] |
| 49 | + currentPosition = i |
| 50 | + while currentPosition>0 and sortList[currentPosition-1]>currentValue: |
| 51 | + sortList[currentPosition] = sortList[currentPosition-1] |
| 52 | + currentPosition = currentPosition-1 |
| 53 | + sortList[currentPosition] = currentValue |
| 54 | + return sortList |
| 55 | + |
| 56 | +#希尔排序 |
| 57 | +def shellSort(sortList): |
| 58 | + length = len(sortList) |
| 59 | + dist = length // 2 |
| 60 | + |
| 61 | + while dist > 0 : |
| 62 | + for i in range(dist,length): |
| 63 | + j = i |
| 64 | + while j >= dist and sortList[j-dist] > sortList[j] : |
| 65 | + sortList[j-dist],sortList[j] = sortList[j],sortList[j-dist] |
| 66 | + j = j- dist |
| 67 | + dist = dist//2 |
| 68 | + return sortList |
| 69 | +# 计算结果,计算时间 |
| 70 | +def caculateResultAndTime(name,fuction,randomseed): |
| 71 | + print("--------------------",name) |
| 72 | + random.seed(randomseed) |
| 73 | + sortList = [random.randint(0,100) for _ in range(10)] |
| 74 | + print("原始数据:",sortList) |
| 75 | + startTime = time.perf_counter() |
| 76 | + fuction(sortList) |
| 77 | + endTime = time.perf_counter() |
| 78 | + print("排序结果:",sortList,' 花费时间:',endTime-startTime) |
| 79 | + |
| 80 | +if __name__ == '__main__': |
| 81 | + caculateResultAndTime("希尔排序",shellSort,88) |
| 82 | + caculateResultAndTime("插入排序",insertionSort,89) |
| 83 | + caculateResultAndTime("冒泡排序",bubble_sort,90) |
| 84 | + caculateResultAndTime("选择排序",selectionSort,91) |
| 85 | + |
| 86 | + |
| 87 | + |
| 88 | + |
| 89 | + |
0 commit comments