您的位置:首页 > 编程语言 > Python开发

排序算法总结(冒泡排序、直接插入排序、希尔排序)(python实现)

2016-02-29 22:00 896 查看
其实本文叫排序算法总结有点过了,只是用python实现了一遍。本文都是参照一篇csdn博客《数据结构排序算法》,里面详细介绍每种排序算法的原理,并给出了C++的实现,再次膜拜。

# -*- coding: gb2312 -*-

# 交换两个数
def swap(a, b):
return b, a

# 冒泡排序
# 进行两次嵌套排序
# 每一次排序将最大或最小移到最右端
# 下次排序排序 Length+1-i
class Sort(object):

def __init__(self, list):
self.list = list

def bubbleSort(self, btype=True):
l = self.list[:]
if not self.list:
return l;

length = len(l)
for i in range(0, length-1):
print_flag = False
for j in range(0, length-i-1):
if btype: # 升序
if l[j] > l[j+1]:
print_flag = True
l[j], l[j+1] = swap(l[j], l[j+1])

else:    # 降序
if l[j] < l[j+1]:
print_flag = True
l[j], l[j+1] = swap(l[j], l[j+1])

if print_flag: print '一趟冒泡排序后: ',l
print l

def bubbleSort2(self, btype=True):
l = self.list[:]
if not self.list:
return l;
length = len(l)
for i in range(length-1,0, -1):
for j in range(0, i):
if btype: # 升序
if l[j] > l[j+1]:
l[j], l[j+1] = swap(l[j], l[j+1])
else:    # 降序
if l[j] < l[j+1]:
l[j], l[j+1] = swap(l[j], l[j+1])
print l

# 直接插入排序
# 在一个已经有序的数据序列插入一个数,使插入数据后序列仍然有序
# 首先,将第0个元素视为一个已经排好序的序列
# 从1到length-1依次进行直接插入操作
# 每次插入,以之前排好序的序列为基础,如序列为[0:i-1]
# 找合适的位置插入第i个元素
# 循环以上步骤直到循环结束
def insertSort(self, btype=True):
l = self.list[:]
if not self.list:
return l
length = len(l)

for i in range(1, length):
print_flag = False
for j in range(i, 0, -1):
if btype:
if l[j] < l[j-1]:
print_flag = True
l[j-1], l[j] = swap(l[j-1], l[j])
else:
break
else:
if l[j] > l[j-1]:
print_flag = True
l[j-1], l[j] = swap(l[j-1], l[j])
else:
break
if print_flag: print '一趟插入排序后: ', l
print l

# 希尔排序
# 希尔排序(Shell Sort)是插入排序的一种。
# 是针对直接插入排序算法的改进。该方法又称缩小增量排序,因DL.Shell于1959年提出而得名。
# 先取一个小于n的整数d1作为第一个增量,把文件的全部记录分成d1个组。所有距离为d1的倍数的记录放在同一个组中。
# 先在各组内进行直接插入排序;然后,取第二个增量d2<d1重复上述的分组和排序,
# 直至所取的增量dt=1(dt<dt-l<…<d2<d1),即所有记录放在同一组中进行直接插入排序为止。
def shellSort(self, btype=True):
l = self.list[:]
if not self.list:
return l
n = len(l)

gap = n/2

while gap > 0:
print_flag = False
for i in range(gap, n):
j = i
while j>=gap:
if btype:
if l[j] < l[j-gap]:
print_flag = True
l[j], l[j-gap] = swap(l[j], l[j-gap])
else:
break
else:
if l[j] > l[j-gap]:
print_flag = True
l[j], l[j-gap] = swap(l[j], l[j-gap])
else:
break
j -= gap
print '一趟希尔排序后(gap=%d): ' %gap, l

gap /= 2
print l

结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: