1.插入排序 时间复杂度O(n^2)
def insertSorting(l):
length = len(l)
for i in range(length):
for j in range(i):
if l[i] >= l[j]:
continue
break
if i != 0:
for k in range(j,i):
l[i], l[k] = l[k], l[i]
2.冒泡排序 时间复杂度O(n^2)
def bubbleSorting(l):
length = len(l)
for i in range(length):
for j in range(i,length):
if l[j] < l[i]:
l[i], l[j] = l[j], l[i]
3.快速排序 时间复杂度O(nlgn)
def quickSort(l, start, stop):
if start >= stop:
return l
pivot, low, high = l[start], start, stop
while low < high:
while low<high and l[high] >= pivot:
high -= 1
l[low] = l[high]
while low < high and l[low] <= pivot:
low += 1
l[high] = l[low]
l[high] = pivot
quickSort(l, start, low-1)
quickSort(l, low+1, stop)
return l
### 4.选择排序 时间复杂度O(n^2)
```python
def selectionSort(l):
length = len(l)
for i in range(length):
m = i
for j in range(i,length):
m = j if l[j]<l[m] else m
l[m], l[i] = l[i], l[m]
5.堆排序 时间复杂度O(nlgn)
def heapfy(nums, i, size):
left, right = 2 * i + 1, 2 * i + 2
largest = left if left < size and nums[left] > nums[i] else i
largest = right if right < size and nums[right] > nums[largest] else largest
if largest != i:
nums[largest], nums[i] = nums[i], nums[largest]
heapfy(nums, largest, size)
def heapSort(nums):
size = len(nums)
for i in range(size//2)[::-1]:
heapfy(nums, i, size)
for i in range(size)[::-1]:
nums[0], nums[i] = nums[i], nums[0]
size -= 1
heapfy(nums, 0, size)
return nums





近期评论