Download presentation
Presentation is loading. Please wait.
Published byPatricia Davis Modified over 8 years ago
1
CS 261 - Fall 2009 Sorted List Sets
2
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.
3
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???)
4
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.
5
Merge
6
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
7
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
8
Example: Intersection void 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; }}}
9
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?
10
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….
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.