直接插入排序
def insertSort(nums):
'''
直接插入排序,时间复杂度n2
:param nums: 待排序列表
:return:
'''
i = 1
while i < len(nums):
if nums[i] < nums[i - 1]:
povitvalue = nums[i]
nums[i] = nums[i - 1]
j = i - 2
while nums[j] > povitvalue and j >= 0:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = povitvalue
i += 1
return nums
快速排序
def partition(nums, low, high):
'''
交换顺序表nums中的记录,返回枢轴位置
:param nums: 待排序的顺序表
:param low: 开始索引
:param high: 结束索引
:return:
'''
pivotkey = nums[low]
while low < high:
while low < high and nums[high] >= pivotkey:
high -= 1
nums[low] = nums[high]
while low < high and nums[low] <= pivotkey:
low += 1
nums[high] = nums[low]
nums[low] = pivotkey
return low
def QSort(nums, low, high):
'''
快速排序,递归
:param nums:
:param low:
:param high:
:return:
'''
if low < high:
pivotloc = partition(nums, low, high)
QSort(nums, low, pivotloc-1)
QSort(nums, pivotloc + 1, high)
return nums
冒泡排序
def bubbleSort(nums):
'''
冒泡排序,最坏情况下,时间复杂度位n2
:param nums:
:return:
'''
j = len(nums)
while j > 1:
no_exchange = True
for i in range(j-1):
if nums[i] > nums[i+1]:
no_exchange = False
temp = nums[i + 1]
nums[i + 1] = nums[i]
nums[i] = temp
if no_exchange:
break
j -= 1
return nums
简单选择排序
def selectSort(nums):
'''
时间复杂度为n2, 比较次数始终为n(n-1)/2
一趟选择排序,将最小元素放在最前面,与冒泡排序相反
一趟冒泡排序,将最大元素放在最后面
:param nums:
:return:
'''
for i in range(len(nums) - 1):
curList = nums[i:]
curMinIndex = curList.index(min(curList))
if (curMinIndex + i) != i:
temp = nums[curMinIndex+i]
nums[curMinIndex+i] = nums[i]
nums[i] = temp
return nums