快速排序算法的核心思想就是分而治之,将要排序的数组基于一个基准值(一般选择数组的第一元素)进行一份为二(大于基准值的放到右边,小于基准值的放到左边),然后进行两组递归(小于基准值和大于基准值的分别进行二分排序,依次递归,直到每组无法拆分,此时每组的顺序都已排好),二分法思想在很多算法中有应用,例如数结构一分为二,所以二分的时间复杂度为O(n*logn)。
python具体实现快速排序代码如下:
# _*_ coding:utf-8 _*_
def quick_sort(array, i, j):
if i >= j:
return array
mid = array[i]
low = i
high = j
while i < j:
while i < j and array[j] >= mid:
j -= 1
array[i] = array[j]
while i < j and array[i] <= mid:
i += 1
array[j] = array[i]
array[j] = mid
quick_sort(array, low, i-1)
quick_sort(array, i+1, high)
return array
if __name__ == '__main__':
lists = [20, 14, 5, 58, 18, 36, 12, 42, 39]
print("排序前的序列为:")
for i in lists:
print(i, end=" ")
print("\n排序后的序列为:")
for i in quick_sort(lists, 0, len(lists) - 1):
print(i, end=" ")
冒泡排序的核心思想是比较相邻两个元素的大小,相邻的两个元素进行比较,然后把较大的元素放到后面(正向排序),在一轮比较完后最大的元素就放在了最后一个位置
# _*_ coding:utf-8 _*_
def bubble_sort(array):
l = len(array)
for i in range(l-1):
for j in range(l-i-1):
if array[j] >= array[j+1]:
array[j+1], array[j] = array[j], array[j+1]
return array
if __name__ == '__main__':
lists = [20, 14, 5, 58, 18, 36, 12, 42, 39]
print("排序前的序列为:")
for i in lists:
print(i, end=" ")
print("\n排序后的序列为:")
for i in bubble_sort(lists):
print(i, end=" ")
选择排序的核心思想是比较当前元素和该元素之后的所有元素的小大,将最小的元素移到当前位置
def select_sort(array):
l = len(array)
for i in range(l):
for j in range(i+1, l):
if array[j] < array[i]:
array[i], array[j] = array[j], array[i]
return array
if __name__ == '__main__':
lists = [20, 14, 5, 58, 18, 36, 12, 42, 39]
print("排序前的序列为:")
for i in lists:
print(i, end=" ")
print("\n排序后的序列为:")
for i in select_sort(lists):
print(i, end=" ")
def insert_sort(array):
l = len(array)
for i in range(1, l):
for j in range(i, 0, -1):
if array[j] <= array[j-1]:
array[j-1], array[j] = array[j], array[j-1]
return array
if __name__ == '__main__':
lists = [20, 14, 5, 58, 18, 36, 12, 42, 39]
print("排序前的序列为:")
for i in lists:
print(i, end=" ")
print("\n排序后的序列为:")
for i in insert_sort(lists):
print(i, end=" ")