Classic sorting algorithm-cocktail sorting cocktail sort
Cocktail sorting is based on Bubble sorting and bidirectional Loops
Let's take a look at the example. For an array to be arranged, see [2 3 4 5 1].
The first step in the past
Step 1 iteration, 2 <3 do not change
[2 3 4 5 1]
Step 2 iteration, 3 <4 do not change
[2 3 4 5 1]
Step 3 iteration, 4 <5 do not change
[2 3 4 5 1]
Step 4 iteration, 5> 1 Exchange
[2 3 4 1 5]
The first step when I come back is to return after a cocktail arrives, and then to the beginning, back and forth to compare, one back and forth can be arranged with two numbers
Step 5 iteration, 1 <5 without exchange
[2 3 4 1 5]
Step 6 iteration, 1 <4 Exchange
[2 3 1 4 5]
Step 7 iteration, 1 <3 Exchange
[2 1 3 4 5]
Step 8 iteration, 2> 1 Exchange
[1 2 3 4 5]
After sorting, the output result can be [1 2 3 4 5].
How can I judge that the sorting is over?
If no number is exchanged for a round trip, it indicates that the array is sorted. You can set a variable to indicate whether the number has been exchanged.
Back to main directory [classic Sorting Algorithm] [Collection]