python 常见排序实例

时间:2023-12-25 15:53:07

使用Python 基础排序算法设计,冒泡排序,插入排序,快速排序...

需求

对一组无序数据进行排序算法设计,要求如下:

输入:[1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]

输出:[1, 3, 5, 5, 22, 23, 34, 34, 37, 74, 75, 86, 456]

冒泡排序

核心算法:循环比较相邻的两个元素,如果前面一个元素比后面一个元素大,则交换位置。

#!/usr/bin/env python
# -*- coding: utf-8 -*- def bubble_sort(data_source):
length = len(data_source)
for i in range(1, length):
for j in range(length - i):
if data_source[j] > data_source[j + 1]:
data_source[j], data_source[j + 1] = data_source[j + 1], data_source[j]
return data_source if __name__ == '__main__':
test_array = [1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]
print bubble_sort(test_array)

插入排序

核心算法:从头到尾循环,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入,因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

#!/usr/bin/env python
# -*- coding: utf-8 -*- def insert_sort(data_source):
count = len(data_source)
for i in range(1, count):
key = data_source[i]
j = i - 1
while j >= 0:
if data_source[j] > key:
data_source[j], data_source[j + 1] = key, data_source[j]
j -= 1
return data_source if __name__ == '__main__':
test_array = [1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]
print insert_sort(test_array)

快速排序

核心算法:每次循环,取一个基数,将序列分成三部分:比基数小的数序列,基数,比基数大的序列。不断重复对每个序列进行相同的处理,直到每个序列为空,则完成排序

#!/usr/bin/env python
# -*- coding: utf-8 -*- def quick_sort(data_source):
length = len(data_source)
if length == 0:
return []
else:
left = []
right = []
for i in range(1, length):
if data_source[0] > data_source[i]:
left.append(data_source[i])
else:
right.append(data_source[i])
return quick_sort(left) + [data_source[0]] + quick_sort(right) if __name__ == '__main__':
test_array = [1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]
print quick_sort(test_array)