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