Created
February 9, 2013 08:17
-
-
Save ashwch/4744573 to your computer and use it in GitHub Desktop.
Quick Union algorithm : It is used to check whether two nodes are connected or not. If both nodes have the same root then they are connected else not connected. Connecting two nodes means make one's root point to other's root.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Implementation of Quick Union algorithm in python. | |
| Link: https://class.coursera.org/algs4partI-002/lecture/7 | |
| """ | |
| def get_root(lis,item): | |
| """ | |
| return the root of an item | |
| """ | |
| root=item | |
| while lis[root] != root: | |
| root = lis[root] | |
| return root | |
| def connected(lis,item1,item2): | |
| """ | |
| Checks if two items are connected | |
| or not. | |
| Connected means both items have the | |
| same root | |
| """ | |
| root1=get_root(lis,item1) | |
| root2= get_root(lis,item2) | |
| return True if root1==root2 else False | |
| def quick_union(lis,item1,item2): | |
| """ | |
| Join two nodes(join their roots) | |
| """ | |
| root1=get_root(lis,item1) | |
| root2= get_root(lis,item2) | |
| if root1 != root2: | |
| lis[root1]=root2 | |
| else: | |
| print "Already connected" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment