Classic Sort algorithm-cocktail sort Cocktail sort

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.