问题描述:冒泡排序的Python实现
问题分析:冒泡排序的算法原理可以参考《Algorithm-排序算法-冒泡排序》,里面给了Java的算法实现。
代码编写
1.数据产生器
#!/usr/bi/env python3
#filename:data_generator.py
import random,json
class DataGenerator(object):
def __init__(self):
pass
@staticmethod
def generate(filename,num):
items = [random.randint(100,10000000) for _ in range(0,num)]
with open(filename,"w+") as file:
json.dump(items,file)
if __name__ == "__main__":
DataGenerator.generate("D:\\data.txt",10000 )
2.未经过优化的冒泡算法buffle_sort.py
#!/usr/bin/env python3
#filename:bubble_sort.py
import json,time
class BubbleSort(object):
data = ''
def __init__(self, filename):
self.__load__(filename)
pass
def __load__(self,filename):
with open(filename,"r") as file:
self.data = json.load(file)
def sort(self):
starttime = time.time()
length = len(self.data)
for i in range(0,length-1):
for j in range(0,length-1-i):
if self.data[j]>self.data[j+1]:
temp = self.data[j]
self.data[j] = self.data[j+1]
self.data[j+1] = temp
interval = time.time()-starttime
print("%d个随机数据排序,冒泡排序所需时长:%d"%(len,interval))
if __name__ =="__main__":
instance = BubbleSort("D:\\data.txt")
instance.sort()
Python的冒泡排序实现不建议测试数据过大,时间比较长。