מבני נתונים ואלגוריתמים - מחברת קורס/מבני נתונים/מבני נתונים לקבוצות זרות - פסוודו-קוד

מתוך ויקיספר, אוסף הספרים והמדריכים החופשי

להלן הפסוודו-קוד המלא למימוש מבני נתונים לקבוצות זרות ע"י רשומות עם איחוד עפ"י גודל:

	# A global array of n Linked-lists.
1	Lists = Make-Array(n)

	# A global variable indicating how many sets were made.
2	size = 0


# Takes a list (l) and a value (v).
# Modifies all the links in the list so that their value is v.
List-Set-All(l, v)
1	lnk = l.front

2	while lnk != Nil
3		lnk.value = v
4		lnk = lnk.next


# Takes two lists (l1, l2).
# Modifies them so that all the links are in the first list (l1),
#	and the second list (l2) is empty.
List-Union(l1, l2)
1	if l1.back != Nil
2		l1.back.next = l2.front
3	if l2.front != Nil
4		l2.front.prev = l1.back

5	l1.back = l2.back
6	l1.size = l1.size + l2.size

7	l2.front = l2.back = Nil
8	l2.size = 0


# Makes a set.
Make-Set()
	# Make a new list.
1	Lists[++size] = Make-List()

	# Insert in a link whose value is size.
2	Insert-Front(Lists[size], size)

	# Return the (pointer to the) first link.
3	return Lists[size].front


# Finds a set by a "representative" (s).
Find-Set(s)
1	return s.value


# Joins two sets by their "representatives" (s1, s2).
Union(s1, s2)
1	l1 = Lists[s1.value]
2	l2 = Lists[s2.value]

3	if Size(l1) 
		# Exchange the lists.
4		l1 <-> l2

	# Set all values in l2 to be s1.value.
	#
	# (This is one lf List's utility functions).	
5	List-Set-All(l2, s1.value)
	
	# l1 becomes a list whose links are the union of the links
	# 	of (the old) l1 and l2.
	# 	l2 becomes the empty list.
	#
	# (This is one lf List's utility functions).	
6	List-Union(l1, l2)