# 冒泡排序
def sort(arr):
le = len(arr)
for i in range(le-1):
for j in range(le-1-i):
if arr[j] > arr[j+1]:
mid = arr[j+1]
arr[j+1] = arr[j]
arr[j] = mid
return arr
# 选择排序 查找最小值
def sort1(arr):
le = len(arr)
min = 0
for i in range(le):
min = i
for j in range(i+1,le):
if(arr[j]<arr[min]):
min = j
wap = arr[i]
arr[i] = arr[min]
arr[min] = wap
return arr
# 插入排序
def sort2(arr):
le = len(arr)
if le <= 1:
return arr
preIndex = 0
current = 0
for i in range(1 , le):
preIndex = i - 1
current = arr[i]
while preIndex >= 0 and current < arr[preIndex]:
arr[preIndex + 1] = arr[preIndex]
preIndex = preIndex - 1
arr[preIndex + 1] = current
return arr
# 希尔排序
def ShellSort(arr):
le = len(arr)
temp = le // 2
gap = le // 2
while(gap > 0):
for i in range(0,le):
temp = arr[i]
preIndex = i - gap
while(preIndex >= 0 and arr[preIndex] > temp):
arr[preIndex + gap] = arr[preIndex]
preIndex -= gap
arr[preIndex + gap] = temp
gap //= 2
return arr
# 归并排序
def mergeSort(arr):
if len(arr) < 2:
return arr
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
return merge(mergeSort(left),mergeSort(right))
def merge(left,right):
result = []
while len(left)>0 and len(right)>0:
if left[0] <= right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
result += left
result += right
return result
#快速排序方法
def quick_sort_standord(array, low, high):
if low < high:
key_index = partion(array, low, high)
quick_sort_standord(array, low, key_index)
quick_sort_standord(array, key_index + 1, high)
def partion(array, low, high):
key = array[low]
while low < high:
while low < high and array[high] >= key:
high -= 1
if low < high:
array[low] = array[high]
while low < high and array[low] < key:
low += 1
if low < high:
array[high] = array[low]
array[low] = key
return low
排序算法
最新推荐文章于 2024-10-27 21:30:45 发布