冒泡排序
def bubbleSort(nums): if len(nums) <= 1: return nums for i in range(len(nums) - 1): for j in range(len(nums) - i - 1): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] return nums listnum = [5, 3, 8, 7, 9, 2, 18, 6, 8, 10, 55, 12, 58, 47] bubbleSort(listnum)
选择排序
def selectionSort(nums): if len(nums) <= 1: return nums for i in range(0, len(nums)): # 最小值位置索引 minIndex = i for j in range(i + 1, len(nums)): if nums[j] < nums[minIndex]: minIndex = j nums[i], nums[minIndex] = nums[minIndex], nums[i] return nums listnum = [5, 3, 8, 7, 9, 2, 18, 6, 8, 10, 55, 12, 58, 47] selectionSort(listnum)
插入排序
def insertSort(nums): if len(nums) <= 1: return nums for i in range(1, len(nums)): pos = 0 for j in range(i - 1, -1, -1): if nums[i] > nums[j]: pos = j + 1 break temp = nums[i] for x in range(i, pos - 1, -1): nums[x] = nums[x - 1] nums[pos] = temp return nums listnum = [5, 3, 8, 7, 9, 2, 18, 6, 8, 10, 55, 12, 58, 47] insertSort(listnum)
快速排序
def quicksort(nums): if len(nums) <= 1: return nums # 左子数组 left = [] # 右子数组 right = [] # 基准数,数组最后一位 base = nums.pop() # 对原数组进行划分 for x in nums: if x < base: left.append(x) else: right.append(x) # 递归调用 return quicksort(right) + [base] + quicksort(left) listnum = [5, 3, 8, 7, 9, 2, 18, 6, 8, 10, 55, 12, 58, 47] quicksort(listnum)标签:nums,Python,pos,len,listnum,算法,排序,def From: https://www.cnblogs.com/tamya/p/16901753.html