defbubble_sort(nums): if len(nums) <= 1: return nums for i in range(1, len(nums)): for j in range(len(nums) - i): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] return nums
defselect_sort(nums): for i in range(len(nums)): min_index = i for j in range(i, len(nums)): if nums[min_index] > nums[j]: min_index = j nums[i], nums[min_index] = nums[min_index], nums[i] return nums
definsert_sort(cls, nums): for i in range(1, len(nums)): for j in range(i, 0, -1): if nums[j] < nums[j - 1]: nums[j - 1], nums[j] = nums[j], nums[j - 1] else: break return nums
希尔排序
希尔排序是插入排序的一个变种,可以更高效的完成排序。希尔排序的关键在于间隔序列的设定,以确定增量。
选择间隔,确定增量(固定间隔或动态定义间隔);
根据间隔,对序列进行分组,对每组元素进行插入排序;
对新序列重复执行1,2步骤,直到完成排序。
1 2 3 4 5 6 7 8 9 10 11 12 13
defshell_sort(nums): length, gap = len(nums), 1 while gap < length: # 动态生成间隔值 gap = gap * 3 + 1 while gap > 0: for i in range(gap, length: # 执行 for j in range(i, 0, -gap): if nums[j] < nums[j - gap]: nums[j - gap], nums[j] = nums[j], nums[j - gap] else: break gap //= 3 return nums
def_qsort(nums, start, end): base, left, right = nums[start], start, end while left < right: while left < right and nums[right] >= base: right -= 1 if left != right: nums[left], nums[right] = nums[right], nums[left] else: break while left < right and nums[left] <= base: left += 1 if left != right: nums[left], nums[right] = nums[right], nums[left] else: break if left - 1 > start: _qsort(nums, start, left -1) if right + 1 < end: _qsort(nums, right + 1, end) return nums
def_merge(left, right): a, b, ans = 0, 0, [] while a < len(left) and b < len(right): if left[a] < right[b]: ans.append(left[a]) a += 1 else: ans.append(right[b]) b += 1 ans += left[a:] or right[b:] return ans
defmerge_sort(nums): if len(nums) <= 1: return nums left = merge_sort(nums[:len(nums) // 2]) right = merge_sort(nums[len(nums) // 2:]) return _merge(left, right)