冒泡、选择、插入、归并、快速、计数、基数、桶、堆、希尔
1、冒泡
def sort_num2(nums):
# select max value bubble O(n^2) safety
n = len(nums)
for i in range(n):
for j in range(i+1, n):
if nums[i] < nums[j]:
nums[i], nums[j] = nums[j], nums[i]
return nums
2、选择
def sort_num1(nums):
# select max value and swap O(n^2) un_safety
n = len(nums)
for i in range(n):
max_i = i
for j in range(i+1, n):
if nums[max_i] < nums[j]:
max_i = j
if max_i != i:
nums[i], nums[max_i] = nums[max_i], nums[i]
return nums
3、插入
def sort_num3(nums):
# insert O(n^2) safety
n = len(nums)
for i in range(1, n): # need to insert nums index
j = i
while j > 0:
if nums[j] > nums[j-1]:
nums[j], nums[j-1] = nums[j-1], nums[j]
j -= 1
return nums
def sort_num4(nums):
# insert swap j and j+1 O(n^2) safety
n = len(nums)
for i in range(n-1):
for j in range(n-i-1):
if nums[j] < nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
return nums
4、归并
def sort_num5(nums):
# merge divide and conquer O(nlog n) safety
n = len(nums)
if n == 1:
return nums
num1 = sort_num2(nums[:n // 2])
num2 = sort_num2(nums[n // 2:])
j1 = j2 = 0
for i in range(n):
if j1 < len(num1) and j2 < len(num2):
if num1[j1] > num2[j2]:
nums[i] = num1[j1]
j1 = j1 + 1
else:
nums[i] = num2[j2]
j2 = j2 + 1
elif j1 < len(num1):
nums[i] = num1[j1]
j1 = j1 + 1
else:
nums[i] = num2[j2]
j2 = j2 + 1
return nums
5、快速
def sort_num6(nums, left=None, right=None):
# quick divide and conquer O(nlog n) un_safety
left = 0 if not isinstance(left, (int, float)) else left
right = len(nums)-1 if not isinstance(right, (int, float)) else right
if left < right:
index = part(nums, left, right)
sort_num6(nums, left, index-1)
sort_num6(nums, index+1, right)
return nums
def part(nums, left, right):
pivot = left # base index
index = pivot + 1 # search index
for i in range(left+1, right+1):
if nums[i] > nums[pivot]:
nums[i], nums[index] = nums[index], nums[i]
index += 1
nums[pivot], nums[index - 1] = nums[index - 1], nums[pivot]
return index - 1
6、希尔
def shell_sort(arr):
# shell ---- insert O(nlogn) un_safety
n = len(arr)
gap = n >> 1
while gap > 0:
for i in range(gap, n):
tmp = arr[i]
j = i-gap
while (j >= 0) and (arr[j] > tmp):
arr[j+gap] = arr[j]
j -= gap
arr[j+gap] = tmp
gap >>= 1
return arr