Classic Sort algorithm-cocktail sort Cocktail sort
Cocktail sort based on bubble sort, bidirectional loop
Let's look at an example, given an array of rows [2 3 4 5 1]
Every step of the first trip to the past
First iteration, 2 < 3 no swap
[2 3 4 5 1]
Second iteration, 3 < 4 no swap
[2 3 4 5 1]
Third iteration, 4 < 5 no swap
[2 3 4 5 1]
Fourth step iteration, 5 > 1 swap
[2 3 4 1 5]
The first step back when the cocktail at the end of the return back, and then the end of the past, back and forth, a back and forth can row two numbers
Fifth step iteration, 1 < 5 no swap
[2 3 4 1 5]
Sixth step iteration, 1 < 4 swap
[2 3 1 4 5]
Seventh step iteration, 1 < 3 swap
[2 1 3 4 5]
Eighth step iteration, 2 > 1 swap
[1 2 3 4 5]
Sorted, sequential output can be obtained [1 2 3 4 5]
How can I tell if the sorting is over?
If a trip does not exchange any number, it means that the array has been ordered, you can set a variable to indicate that there is no exchange
Code for reference only
Static voidCocktail_sort (int[] unsorted) { BOOLswapped =false; Do { for(inti =0; I < unsorted. Length-1; i++) { if(Unsorted[i] > unsorted[i +1]) { inttemp =Unsorted[i]; Unsorted[i]= Unsorted[i +1]; Unsorted[i+1] =temp; Swapped=true; }} swapped=false; for(intj = unsorted. Length; J >1; j--) { if(Unsorted[j] < unsorted[j-1]) { inttemp =Unsorted[j]; UNSORTED[J]= Unsorted[j-1]; Unsorted[j-1] =temp; Swapped=true; } } } while(swapped); } Static voidMain (string[] args) { int[] x = {6,2,4,1,5,9 }; Selection_sort (x); foreach(varIteminchx) {Console.WriteLine (item); } console.readline (); }
Classic Sort algorithm-cocktail sort Cocktail sort