cs 261 - fall 2009 sorted list sets. what is the use of sorting? remember we sorted a dynamic array...
DESCRIPTION
Forshadowing of next topic Think carefully about this. Why can’t we do a binary search on a list? (What if we COULD??? Would it be any better than a binary search on a dynamic array? Why???)TRANSCRIPT
CS 261 - Fall 2009
Sorted List Sets
What is the use of sorting?
• Remember we sorted a dynamic array so that we could use binary search.
• There would seem to be little reason to kept a list is sorted order, since searching still requires an O(n) traversal of all links.
Forshadowing of next topic
• Think carefully about this.• Why can’t we do a binary search on a
list?• (What if we COULD??? Would it be any
better than a binary search on a dynamic array? Why???)
But there was another reason
• But, if you think about it, there is another reason why you might want to keep a collection in order
• That is, an ordered collection allows us to do a very rapid merge operation.
Merge
Idea of merge
• Run down both lists in order• Keep a “finger” pointing to each list.• Always advance the finger that points to
the smaller element• Creates a merge in O(n) time
Set Operations are merge-like
• Each of the set operations are merge-like• Intersection - keep only if found in both lists• Union - keep if found in either, keep only one
copy if found in both• Difference - keep only if found in one• Subset - test each value to see if in second
Example: Intersectionvoid listIntersection (struct list *list1, struct list
*list2, struct list * result) { /* assumes list1 and list2 are sorted and result is
empty */ struct ptr1 = list1->frontSentinel->next; struct ptr2 = list2->frontSentinel->next; while (ptr1 != list1->backSentinel && ptr2 != list2-
>backSentinel) { if (LT(ptr1->value, ptr2->value)) { ptr1 = ptr1->next; } else if (EQ(ptr1->value, ptr2->value)) { listAddBack(result, ptr1->value); ptr1 = ptr1->next; ptr2 = ptr2->next; } else { ptr2 = ptr2->next; }}}
Union just a bit more work
• Union has some extra loops at the end• Can anybody explain why?• What other operations need to do this?
Short day today
• Think about what would be involved in writing the set operations (union, intersection, difference, subset) as a type of merge.
• Not going to do the worksheet today, but maybe a future assignment….