Cocktail sort, also called directional bubble sort , is an improvement of the bubbling sort. The difference between this algorithm and the bubbling sort is from low to high and then high to low , while bubble sorting is only low to high to compare each element in the sequence. He can get a little bit better performance than bubble sort.
Python code:
1 defBubble_sort_pro (num_array):2Flag =True3 forIinchRange (len (num_array)//2):4 ifflag:5Flag =False6 #queue the maximum to the end of the queue7 forJinchRange (I, Len (num_array)-i-1):8 ifNum_array[j]>num_array[j+1]:9NUM_ARRAY[J], num_array[j+1] = num_array[j+1], Num_array[j]TenFlag =True One #rank the minimum to the top of the team A forJinchRange (len (num_array) -1-i, I,-1): - ifNUM_ARRAY[J] < Num_array[j-1]: -NUM_ARRAY[J], num_array[j-1] = num_array[j-1], Num_array[j] theFlag =True - Else: - Break - + - defMain (): +A = [6, 5, 3, 1, 8, 7, 2, 4] A at Bubble_sort_pro (a) - forIinchRange (len (a)): - Print(A[i]) - - - if __name__=='__main__': inMain ()
Algorithm----(2) Cocktail ordering