码迷,mamicode.com
首页 > 编程语言 > 详细

利用快速排序求两集合交集

时间:2015-04-19 17:52:09      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

1.主程序
%% 求两个集合快速排序
tic
arrayList1 = [49,38,65,97,76,13,27,49,100,67];
arrayList1 = quickSort(arrayList1,1,length(arrayList1));
arrayList2 = [49,34,76,27,23,566,67];
arrayList2 = quickSort(arrayList2,1,length(arrayList2));

%% 求两个集合交集;
length_arrayList1 = length(arrayList1);
length_arrayList2 = length(arrayList2);
union = [];
i = 1;
j = 1;
while true
    if i < length_arrayList1 && j < length_arrayList2
        if arrayList1(i) < arrayList2(j)
            i = i + 1;
        elseif arrayList1(i) > arrayList2(j)
            j = j + 1;
        else
            union = [union,arrayList1(i)];
            i = i + 1;
            j = j + 1;
        end
    else
        break;
    end
end
toc
快速排序函数
function  arrayList = quickSort(arrayList,low,high)
% pivotpos = 1;
if (low < high)
    [pivotpos,arrayList] = partition(arrayList,low,high);
    arrayList  = quickSort(arrayList,low,pivotpos - 1);
    arrayList  = quickSort(arrayList,pivotpos + 1,high);
end
end
划分函数;
function [low,new_arrayList] = partition(arrayList,low,high)
if nargin == 1
    low = 1;
    high = length(arrayList);
end
pivot = arrayList(low);             %用区间第1个记录做基准;
while low < high                    %从区间两段交替向中间扫描,直至low =hing
    while low <high && arrayList(high) >= pivot
        high = high - 1;
    end
    if low < high                        %表示找到arrayList[hihg]< pivot;
        temp = arrayList(low);
        arrayList(low) = arrayList(high);
        arrayList(high) = temp;
        low = low + 1;
    end
    while low < high && arrayList(low) <= pivot
        low = low + 1;
    end
    if low < high
        temp = arrayList(high);
        arrayList(high) = arrayList(low);
        arrayList(low) = temp;
        high = high -1;
    end
end
new_arrayList = arrayList;
end

求指教有什么速度更快的方法求解集合交集。。

利用快速排序求两集合交集

标签:

原文地址:http://www.cnblogs.com/Kermit-Li/p/4439457.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!