[排序]鸡尾酒排序算法实现

版权声明:转载请说明Zhonglihao原创 https://blog.csdn.net/xeonmm1/article/details/83450731
作者 zhonglihao
算法名 鸡尾酒排序 Cocktail Sort
分类 排序
复杂度 % 大概是1/2 * n^2时间复杂度
形式与数据结构 Matlab代码
特性 来回顺序倒序排序
具体参考出处 民间
备注  
clc;clear;close all;

n       = 1000;
data    = rand(1,n);
bar(data);

add_odd = 0;% 奇偶分开排序
sorted_count = 0;% 已有序
sort_circle = 0;

while(1)
    
    if(add_odd == 0)
        sort_circle = sort_circle + 1;
        sorted_count = 1;
        for i = 2:1:n
            if(data(i-1)>data(i))
                temp = data(i-1);
                data(i-1) = data(i);
                data(i) = temp;
            else
                sorted_count = sorted_count + 1;
            end
        end
        
        if(sorted_count==n)
            break;
        end
        add_odd = 1;
    else
        sort_circle = sort_circle + 1;
        sorted_count = 1;
        for i = n:-1:2
            if(data(i-1)>data(i))
                temp = data(i-1);
                data(i-1) = data(i);
                data(i) = temp;
            else
                sorted_count = sorted_count + 1;
            end
        end
        
        if(sorted_count==n)
            break;
        end
        
        add_odd = 0;
    end
end
bar(data);
disp(sort_circle);

猜你喜欢

转载自blog.csdn.net/xeonmm1/article/details/83450731