Classic sorting algorithm-cocktail sorting cocktail sort

Source: Internet
Author: User

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]

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.