Cocktail sorting (improved Bubble Sorting)

Source: Internet
Author: User

Classic sorting algorithm-cocktail sorting CocktailSort
The principle of cocktail sorting (improved Bubble Sorting) is to sort arrays in two-way Bubble sorting, also known as cocktail sorting.
The sample code is as follows: # include <IOSTREAM>
Using namespace std;
/** // Cocktail Sorting/bidirectional bubble sorting (improved Bubble Sorting)
Void CocktailSort (int * a, int nsize)
{
Int tail = nsize-1;
For (int I = 0; I <tail ;)
{
For (int j = tail; j> I; -- j) // in the first round, first sort the smallest data to the front.
{
If (a [j] <a [J-1])
{
Int temp = a [j];
A [j] = a [J-1];
A [J-1] = temp;
}
}
+ + I; // the data in the original I has been sorted, and 1 is added.

For (j = I; j <tail; ++ j) // the second round to route the largest data to the back
{
If (a [j]> a [j + 1])
{
Int temp = a [j];
A [j] = a [j + 1];
A [j + 1] = temp;
}
}

Tail --; // The data at the original tail has been sorted and reduced by 1.
}
}
Void OutPut (int * B, int nLength)
{
For (int I = 0; I <nLength; I ++)
{
Cout <B [I] <'\ T ';
}
Cout <endl;
}
Int main ()
{
Int nData [] = };

CocktailSort (nData, sizeof (nData)/sizeof (nData [0]);
OutPut (nData, sizeof (nData)/sizeof (nData [0]);
Return 1;
}

 


From CodeBeauty

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.