#非常不错的视频讲解 https://www.bilibili.com/video/BV15u41147AG/?spm_id_from=pageDriver&vd_source=a8b9123058273b1fa0e1233c20ec2d2d
#(时间、空间复杂度)
#排序方法
#插入排序、冒泡排序、归并排序、快速排序
#插入排序
def insert_sort(arr):
for i in range(len(arr)):
j = i
while j > 0 and arr[j] < arr[j-1]:
tmpData = arr[j]
arr[j] = arr[j-1]
arr[j-1] = tmpData
j -= 1
return arr
#冒泡排序(也可以理解为下沉)
def bubble_sort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-i-1):
if arr[j] > arr[j+1]:
tmpData = arr[j + 1]
arr[j+1] = arr[j]
arr[j] = tmpData
return arr
#选择排序
def select_sort(arr):
for i in range(len(arr)-1):
min_index = i
#选择待排序中的最小值
for j in range(i+1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
tmpData = arr[i]
arr[i] = arr[min_index]
arr[min_index] = tmpData
return arr
#希尔排序(分组 + 插入排序,这里在做插入排序之前先进行组内运算)
def shell_sort(arr):
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
j = i
while j >= gap and arr[j] < arr[j - gap]:
arr[j], arr[j-gap] = arr[j-gap], arr[j]
j -= gap
gap //= 2
print(arr)
return arr
#归并排序
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
#快速排序
def quick_sort(arr, left, right):
if left >= right:
return arr
pivot = arr[left]
i, j =left, right
while i < j:
while i < j and arr[j] >= pivot:
j -= 1
arr[i] = arr[j]
while i < j and arr[i] < pivot:
i += 1
arr[j] = arr[i]
arr[i] = pivot
quick_sort(arr, left, i-1)
quick_sort(arr, i+1, right)
return arr
arr=[100,4,0,10,90,30,10,5,34,4,5,2,14,14,115,53,15]
# print(insert_sort(arr))
# print(bubble_sort(arr))
# print(select_sort(arr))
# print(shell_sort(arr))
#print(merge_sort(arr))
print(quick_sort(arr, 0, len(arr)-1))