排序算法--鸡尾酒排序
基本思想:
1.鸡尾酒排序等于是冒泡排序的轻微变形。不同的地方在于从低到高后然后从高到低,而冒泡排序则仅从低到高去比较序列里每一个元素。
算法复杂度:
最糟或平均多花费的次数是O(f(n2)),但是如果序列式已经排序号的是,会接近O(n)。
具体实现:
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;
}
}

浙公网安备 33010602011771号