算法:排序加二分查找
#冒泡排序
#1可以将序列中的元素进行两两比较,将两个数比较出的最大值逐步和最小值替换,直到序列中的
# 最大值找出放置到序列最后的位置
#2 将上述操作重复执行N次,就可以实现排序
def sort(alist): length = len(alist) for j in range(length-1): for i in range(length-1): if alist[i] > alist[i+1]: alist[i],alist[i+1] = alist[i+1],alist[i] return alist alist = [3,8,5,7,6] print(sort(alist))
二分查找法 概念:只能作用在有序集合中
# def findValue(alist, item): # left = 0 #序列中第一个元素下标 # right = len(alist) - 1 #最后一个元素下标 # find = False # while left <= right: # mid = (left + right) // 2 #中间元素下标 # if item < alist[mid]: #查找的值小于中间元素,查找的值存在于中间元素左侧 # right = mid - 1 # elif item > alist[mid]: #大于中间元素 在中间元素右侧 # left = mid + 1 # else: # find = True # break # return find # alist = [1, 2, 3, 4, 5, 6, 7,8,9,10,11,12] # print(findValue(alist, 45))
#选择排序 概念 将乱序序列最大的值找出,直接将最大值和序列最后的一个元素交换位置,达到最大值放置到序列最后位置的效果
# def sort1(alist): # # print(len(alist)) # for j in range(len(alist)-1): # # print(j) # max_indedx = 0 # for i in range(1,len(alist)-j): # # print(i) # if alist[max_indedx] < alist[i]: # max_indedx = i # alist[max_indedx],alist[len(alist)-j-1] = alist[len(alist)-j-1],alist[max_indedx] # return alist # alist = [10,8,9,3] # print(sort1(alist))
#插入排序 概念:需要将无序部分的元素逐一插到有序部分中,最终变为有序序列
# def sort(alist): # for i in range(1,len(alist)): # while i > 0: # if alist[i] < alist[i-1]: # alist[i],alist[i-1] = alist[i-1],alist[i] # i-=1 # else: # break # return alist # alist = [5,4,8,7,1,6] # print(sort(alist))
#希尔排序:新概念:增量(gap),增量初始的值为乱序序列元素个数除以2
# 增量的含义:表示间隔,分组的数组
# 插入排序就是增量为1的希尔排序
# def sort(alist): # gap = len(alist) // 2 # while gap>=1: # for i in range(gap,len(alist)): # while i > 0: # if alist[i] < alist[i-gap]: # alist[i],alist[i-gap] = alist[i-gap],alist[i] # i = i - gap # else: # break # gap = gap //2 # return alist # alist = [5,4,8,7,1,6] # print(sort(alist))