Week1-2Quick Find

来源:互联网 发布:hp c7000 网络配置 编辑:程序博客网 时间:2024/05/17 22:05

Quick Find(eager approach)

Data Structure

-Integer Array id[] of size N
-Interpretation: p and q are connected iff they have the same id

Example

这里写图片描述


Find

connected( p, q )

Check if p and q have the same id

Union

union( p, q )

To merger component containing p and q, change all entries whose id equals id[p] to id[q](a lot of entries whose value may be changed)


Quick Find Implementation

    public class QuickFindUF    {        private int[] id;        public QuickFindUF( int N )        {            id = new int[N];            for( int i = 0 ; i < N; i++ )            {                // Set id of each object to itself(N accesses)                id[i] = i;            }        }        public boolean connected( int p, int q )        {            // Check if p and q are connected(2 accesses)            return id[p] == id[q];        }        public void union( int p, int q )        {            // Change all entries with id[p] to id[q]( at most 2N+2 accesses)            int pid = id[p],                qid = id[q];            for( int i = 0; i < id.length; i++ )            {                if( id[i] == pid )                {                    id[i] = qid;                }            }        }    }

Cost

Algorithm initialize union find quick-find O(N) O(N) O(1)

Union is too expansive!!!
Quadratic time algorithms are too slow, because they don’t scale with the technology.
这里写图片描述

0 0