首页 > 其他 > 详细

排序算法--鸡尾酒排序

时间:2014-03-20 03:45:58      阅读:392      评论:0      收藏:0      [点我收藏+]

基本思想:

1.鸡尾酒排序等于是冒泡排序的轻微变形。不同的地方在于从低到高后然后从高到低,而冒泡排序则仅从低到高去比较序列里每一个元素。

算法复杂度:

最糟或平均多花费的次数是O(f(n2)),但是如果序列式已经排序号的是,会接近O(n)。

具体实现:

bubuko.com,布布扣
function cocktail_sort(list, list_length){ // the first element of list has index 0
    bottom = 0;
    top = list_length - 1;
    swapped = true; 
    while(swapped == true) // 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;
            }
        }
        // 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; 
        for(i = top; i > bottom; i = i - 1)
        {
            if(list[i] < list[i - 1]) 
            {
                swap(list[i], list[i - 1]);
                swapped = true;
            }
        }
        // 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;  
    }
}
bubuko.com,布布扣

排序算法--鸡尾酒排序,布布扣,bubuko.com

排序算法--鸡尾酒排序

原文:http://www.cnblogs.com/fang-beny/p/3612247.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!