目录
基本概念:
稳定性
内排序:待排序的所有记录全部放置在内存中
外排序:在内外存之间多次交换数据
冒泡排序:
两两比较相邻的元素,如果反序就交换,直到没有反序。
题目:给定一个长度为 n 的数组,请你编写一个函数,返回该数组按升序排序后的结果。
输入:[5,2,3,1,4]
返回值:[1,2,3,4,5]
class Solution:
def MySort(self , arr: List[int]) -> List[int]:
# write code here
for i in range(1, len(arr)):
for j in range(0, len(arr)-i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
简单选择排序:
在未排序序列中找到最小元素放到起始位置,从剩余元素中寻找最小元素,直至所有元素排序完毕。
class Solution:
def MySort(self , arr: List[int]) -> List[int]:
# write code here
for i in range(len(arr)-1):
minIndex = i
for j in range(i+1, len(arr)):
if arr[j] < arr[minIndex]:
minIndex = j
if i != minIndex:
arr[i], arr[minIndex] = arr[minIndex], arr[i]
return arr
直接插入排序:
将每个元素插入已经排序好的序列中。
class Solution:
def MySort(self , arr: List[int]) -> List[int]:
# write code here
for i in range(len(arr)):
preIndex = i-1
current = arr[i]
while preIndex >= 0 and arr[preIndex] > current:
arr[preIndex+1] = arr[preIndex]
preIndex-=1
arr[preIndex+1] = current
return arr