鸡尾酒排序原理:http://bubkoo.com/2014/01/15/sort-algorithm/shaker-sort/
双向冒泡排序 (Bidirectional Bubble Sort)、波浪排序 (Ripple Sort)、摇曳排序 (Shuffle Sort)、飞梭排序 (Shuttle Sort) 和欢乐时光排序 (Happy Hour Sort)
my stupid code: same problem to bubble sort: 如果直接输入一个排好的序列, 答案可以直接输出,而我的代码需要运行一定的次数。
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 10:14:28 2019
@author: yue zhang
E-mails: yuezh2015@163.com
"""
import numpy as np
def cocktail_shaker_sort(data):
data_num = len(data)
if data_num <2:
return data
for m in range(0,int(data_num/2+1)):
for i in range(m,data_num-m-1):
if data[i]>data[i+1]:
data[i],data[i+1] = data[i+1],data[i]
print(data)
for j in range(data_num-m-1,m,-1):
if data[j]<data[j-1]:
data[j],data[j-1] = data[j-1],data[j]
print(data)
return data
if __name__ == '__main__':
#data = [10,20,50,3,5,7,9,11,88,55,77,56,1,2,4,555,19, 25, 26, 29 ,38 ,50 ,80, 91 ,86, 78 ,66 ,46, 32 ,19 ,15 , 7]
data =[45, 19, 77, 81, 13, 28, 18, 19, 77]
data= cocktail_shaker_sort(data)
answer:
from __future__ import print_function
def cocktail_shaker_sort(unsorted):
"""
Pure implementation of the cocktail shaker sort algorithm in Python.
"""
for i in range(len(unsorted)-1, 0, -1):
swapped = False
for j in range(i, 0, -1):
if unsorted[j] < unsorted[j-1]:
unsorted[j], unsorted[j-1] = unsorted[j-1], unsorted[j]
swapped = True
for j in range(i):
if unsorted[j] > unsorted[j+1]:
unsorted[j], unsorted[j+1] = unsorted[j+1], unsorted[j]
swapped = True
if not swapped:
return unsorted
if __name__ == '__main__':
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
cocktail_shaker_sort(unsorted)
print(unsorted)
https://github.com/TheAlgorithms/Python/blob/master/sorts/cocktail_shaker_sort.py
改:
import numpy as np
def cocktail_shaker_sort(data):
data_num = len(data)
if data_num <2:
return data
for m in range(0,int(data_num/2+1)):
aaa = False
for i in range(m,data_num-m-1):
if data[i]>data[i+1]:
data[i],data[i+1] = data[i+1],data[i]
aaa = True
# print(data)
for j in range(data_num-m-1,m,-1):
if data[j]<data[j-1]:
data[j],data[j-1] = data[j-1],data[j]
aaa = True
print(data)
if aaa == False:
return data
return data
if __name__ == '__main__':
#data = [10,20,50,3,5,7,9,11,88,55,77,56,1,2,4,555,19, 25, 26, 29 ,38 ,50 ,80, 91 ,86, 78 ,66 ,46, 32 ,19 ,15 , 7]
#data =[45, 19, 77, 81, 13, 28, 18, 19, 77]
data =[ 13,15 , 18, 19, 77,88,99]
data= cocktail_shaker_sort(data)