鸡尾酒排序
鸡尾酒排序也就是定向冒泡排序, 鸡尾酒搅拌排序, 搅拌排序 (也可以视作选择排序的一种变形), 涟漪排序, 来回排序 or 快乐小时排序, 是冒泡排序的一种变形。此演算法与冒泡排序的不同处在于排序时是以双向在序列中进行排序。
原理
使用鸡尾酒排序为一列数字进行排序的过程可以通过右图形象的展示出来:数组中的数字本是无规律的排放,先找到最小的数字,把他放到第一位,然后找到最大的数字放到最后一位。然后再找到第二小的数字放到第二位,再找到第二大的数字放到倒数第二位。以此类推,直到完成排序。
i. 先对数组从左到右进行升序的冒泡排序;
ii. 再对数组进行从右到左的降序的冒泡排序;
iii. 以此类推,持续的、依次的改变冒泡的方向,并不断缩小没有排序的数组范围;
例:
88 7 79 64 55 98 48 52 4 13
第一趟: 7 79 64 55 88 48 52 4 13 98
第二趟: 4
7 79 64 55 88 48 42 13 98
第三趟: 4
7 64 55 79 48 42 13 88 98
第四趟: 4
7 13 64 55 79 48 42 88
98
第五趟: 4
7 13 55 64 48 42 79
88 98
第六趟: 4
7 13 42 55 64 48 79
88 98
第七趟: 4
7 13 42 55 48 64
79 88 98
第八趟: 4
7 13 42 48 55
64 79 88 98
编程:
function cocktail_sort(list, list_length) // the first element of list has index 0
{
bottom = 0;
top = list_length - 1;
swapped = true;
bound = 0; //优化循环次数,记录已经排序的边界,减少循环次数
while(swapped) // if no elements have been swapped, then the list is sorted
{
swapped = false;
for(i = bottom; i < top; i = i + 1)
{
if(list[i] > list[i+1]) // test whether the two elements are in the correct order
{
swap(list[i], list[i+1]); // let the two elements change places
swapped = true;
bound = i;
}
}
// decreases top the because the element with the largest value in the unsorted
// part of the list is now on the position top
//top = top - 1;
top = bound;
for(i = top; i > bottom; i = i - 1)
{
if(list[i] < list[i-1])
{
swap(list[i], list[i-1]);
swapped = true;
bound = i;
}
}
// increases bottom because the element with the smallest value in the unsorted
// part of the list is now on the position bottom
//bottom = bottom + 1;
bottom = bound;
}
}
与冒泡的区别
鸡尾酒排序等于是冒泡排序的轻微变形。不同的地方在于从低到高然后从高到低,而冒泡排序则仅从低到高去比较序列里的每个元素。他可以得到比冒泡排序稍微好一点的效能,原因是冒泡排序只从一个方向进行比对(由低到高),每次循环只移动一个项目。以序列(2,3,4,5,1)为例,鸡尾酒排序只需要访问两次(升序降序各一次 )次序列就可以完成排序,但如果使用冒泡排序则需要四次。
复杂度
鸡尾酒排序最糟或是平均所花费的次数都是O(n²),但如果序列在一开始已经大部分排序过的话,会接近O(n)。