本文主要是介绍冒泡排序和鸡尾酒排序(code),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
昨天回顾了下冒泡排序和鸡尾酒排序,用面向对象的方式写了一下,并且优化了代码,记录一下~
一、冒泡排序
# 冒泡排序
class BubbleSort(object):def __init__(self, data_list):self.data_list = data_listself.length = len(data_list)# 简单粗暴的排序方式def b_sort(self):data_list = list(self.data_list)for i in range(self.length):print('**************第%s轮循环**************' % (i + 1))index_len = self.lengthfor index in range(index_len - 1):print(index)if data_list[index] > data_list[index + 1]:data_list[index], data_list[index + 1] = data_list[index + 1], data_list[index]return data_list# 优化后美丽动人又可爱的冒泡排序def new_b_sort(self):data_list = list(self.data_list)for i in range(self.length):print('**************第%s轮循环**************' % (i + 1))index_len = self.lengthmark = Falsefor index in range(index_len - 1 - i):print(index)mark = Trueif data_list[index] > data_list[index + 1]:data_list[index], data_list[index + 1] = data_list[index + 1], data_list[index]mark = Falseif mark:breakreturn data_listdata_list = [2, 3, 1, 7, 4, 3]
bubblesort = BubbleSort(data_list)
res1 = bubblesort.b_sort()
print(res1)
res2 = bubblesort.new_b_sort()
print(res2)
二、鸡尾酒排序
# 鸡尾酒排序
class CocktailSort(object):def __init__(self, data_list):self.data_list = data_listself.length = len(data_list)# 简单粗暴的排序方式def c_sort(self):data_list = list(self.data_list)for i in range(self.length):print('**************第%s轮循环**************' % (i + 1))index_len = self.lengthprint('左--->右')for index in range(index_len - 1):print(index)if data_list[index] < data_list[index + 1]:data_list[index], data_list[index + 1] = data_list[index + 1], data_list[index]print('右--->左')index_len = self.lengthfor index in range(index_len - 1):print(index)if data_list[index] > data_list[index + 1]:data_list[index], data_list[index + 1] = data_list[index + 1], data_list[index]return data_list# 优化后俏皮美丽又懂事的鸡尾酒排序def new_c_sort(self):data_list = list(self.data_list)for i in range(self.length):print('**************第%s轮循环**************' % (i + 1))index_len = self.lengthmark = Falseprint('左--->右')for index in range(index_len - 1- i):mark = Trueprint(index)if data_list[index] < data_list[index + 1]:data_list[index], data_list[index + 1] = data_list[index + 1], data_list[index]mark = Falseprint('右--->左')index_len = self.lengthfor index in range(i, index_len - 1):mark = Trueprint(index)if data_list[index] > data_list[index + 1]:data_list[index], data_list[index + 1] = data_list[index + 1], data_list[index]mark = Falseif mark:breakreturn data_listdata_list = [2, 3, 1, 7, 4, 3]
cocktailsort = CocktailSort(data_list)
res1 = cocktailsort.c_sort()
res2 = cocktailsort.new_c_sort()
print(res1)
print(res2)
这篇关于冒泡排序和鸡尾酒排序(code)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!