#选择n^2
def selectSort(li):
for i in range(len(li)-1):
minLoc = i
for j in range(i+1,len(li)):
if li[j] < li[minLoc]:
li[minLoc],li[j] = li[j],li[minLoc]
# li = [2,1,6,8,3,9,424,243,351,51]
# selectSort(li)
# print(li)
#冒泡n^2
def bubbleSort(li):
for i in range(len(li)-1):
flag = False
for j in range(len(li)-i-1):
if li[j+1] < li[j]:
li[j+1],li[j] = li[j],li[j+1]
flag = True
if not flag:
return
#插入n^2
def insertSort(li):
for i in range(1,len(li)):
tmp = li[i]
j = i-1
while j>=0 and li[j] >tmp:
li[j+1] = li[j]
j = j-1
li[j+1] = tmp
# insertSort(li)
# print(li)
#冒泡是把最大的放到最后面,选择是把最小的放前面,插入
#快速排序,nlogn
def partition(li,left,right):
tmp = li[left]
while left < right:
while left < right and tmp <= li[right]:
right = right - 1
li[left] = li[right]
while left < right and tmp >= li[left]:
left = left + 1
li[right] = li[left]
li[left] = tmp
return left
def quickSort(li,left,right):
if left <right:
mid = partition(li,left,right)
quickSort(li,left,mid-1)
quickSort(li,mid+1,right)
#归并排序nlogn
def merge(li,low,mid,high):
i = low
j = mid + 1
ltmp = []
while i <= mid and j<=high:
if li[i] >= li[j]:
ltmp.append(li[j])
j = j+1
else:
ltmp.append(li[i])
i = i+1
while i<= mid:
ltmp.append(li[i])
i = i+1
while j<=high:
ltmp.append(li[j])
j = j+1
li[low:high+1] = ltmp
def mergeSort(li,low,high):
if low < high:
mid = (low + high) //2
mergeSort(li,low,high)
mergeSort(li,mid+1,high)
merge(li,low,mid,high)
print(li[low:high+1])
li = [10,4,6,3,8,2,5,7]
# mergeSort(li,0,len(li)-1)
#计数排序O(n)
def countSort(li):
count = [0 for i in range(11)]
for x in li:
count[x] +=1
li.clear()
for index,val in enumerate(count):
for i in range(val):
li.append(index)
# countSort(li)
# print(li)
#二分法
def BinarySearch(n,l):
print(l)
if len(l) == 0:
print('not exists')
return
mid_index = len(l) // 2
if n > l[mid_index]:
l = l[mid_index+1:]
BinarySearch(n,l)
elif n < l[mid_index]:
l = l[:mid_index]
BinarySearch(n,l)
else:
print(f'find it,index is l[{l.index(n)}]')
# BinarySearch(6,li)
转载于:https://www.cnblogs.com/beiji/p/10059043.html