zoukankan      html  css  js  c++  java
  • 利用快速排序求两集合交集

    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

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

  • 相关阅读:
    Cuckoo for Hashing_双哈希表
    nyoj113_字符串替换
    nyoj366_D的小L_字典序_全排列
    二叉树的前序 中序 后序 遍历(递归/非递归)
    Java 学习路线
    leetcode 04 Median of Two Sorted Arrays
    ThreadLocal 的机制与内存泄漏
    try finally 执行顺序问题
    Java中的类加载器
    快速理解Java中的七种单例模式
  • 原文地址:https://www.cnblogs.com/Kermit-Li/p/4439457.html
Copyright © 2011-2022 走看看