1. 选择排序
def selectSort(nums): size = len(nums) for i in range(0, size - 1): minIndex = i minValue = nums[i] for j in range(i + 1, size): if nums[j] < minValue: minValue = nums[j] minIndex = j nums[i], nums[minIndex] = nums[minIndex], nums[i]
2. 插入排序
def insertSort(nums): size = len(nums) for i in range(1, size): for j in range(i, 0, -1): if nums[j] >= nums[j - 1]: break nums[j], nums[j - 1] = nums[j - 1], nums[j]
3.冒泡排序
def bubbleSort(nums): size = len(nums) for i in range(0, size): exchange = False for j in range(1, size - i): if nums[j - 1] > nums[j]: nums[j], nums[j - 1] = nums[j - 1], nums[j] exchange = True if not exchange: break
4.快速排序
def quickSort(nums, start, end): if start >= end: return pivot = nums[start] i = start + 1 j = end while i < j: while i < j and nums[i] < pivot: i += 1 while i < j and nums[j] >= pivot: j -= 1 if i < j: nums[i], nums[j] = nums[j], nums[i] pivotIndex = i if nums[pivotIndex] < pivot: nums[start], nums[pivotIndex] = nums[pivotIndex], nums[start] else: if pivotIndex - start > 1: pivotIndex -= 1 nums[start], nums[pivotIndex] = nums[pivotIndex], nums[start] quickSort(nums, start, pivotIndex - 1) quickSort(nums, pivotIndex, end)
nums = [3, 4, 5, 6, 1, 3]
quickSort(nums, 0, len(nums) - 1)
5. 希尔排序
def shellSort(nums): size = len(nums) step = size // 2 while step > 0: for i in range(0, step): for j in range(i + step, size, step): while j - step >= 0 and nums[j] < nums[j - step]: nums[j], nums[j - step] = nums[j - step], nums[j] j -= step step = step // 2
6.归并排序
def mergeSort(nums, start, end): if start >= end: return if end == start + 1: if nums[end] < nums[start]: nums[start], nums[end] = nums[end], nums[start] return mid = (start + end) // 2 mergeSort(nums, start, mid) mergeSort(nums, mid + 1, end) i = start j = mid + 1 midSortNums = [] while i <= mid and j <= end: if nums[i] < nums[j]: midSortNums.append(nums[i]) i += 1 else: midSortNums.append(nums[j]) j += 1 while i <= mid: midSortNums.append(nums[i]) i += 1 while j <= end: midSortNums.append(nums[j]) j += 1 nums[start:end + 1] = midSortNums del midSortNums nums = [3, 4, 5, 6, 1, 3] mergeSort(nums, 0, len(nums) - 1)
7.堆排序
def maxHeapFixDown(nums, index, size): left = 2 * index + 1 right = left + 1 while left < size: change_index = -1 if nums[index] < nums[left]: change_index = left if right < size and nums[right] > nums[left] and nums[right] > nums[index]: change_index = right if change_index == -1: break nums[index], nums[change_index] = nums[change_index], nums[index] index = change_index left = 2 * index + 1 right = left + 1 def createMaxHeap(nums): size = len(nums) for i in range(size // 2, -1, -1): maxHeapFixDown(nums, i, size) def heapSort(nums): createMaxHeap(nums) size = len(nums) for i in range(0, size - 1): nums[0], nums[size - i - 1] = nums[size - i - 1], nums[0] maxHeapFixDown(nums, 0, size - i - 1)