90 likes | 254 Views
Implementing Sets/Maps with an Unsorted Array. Computer Science 4 Mr. Gerb. Reference: Objective: Understand how to implement Maps and Sets using an unsorted array. Implementing Search. Search algorithms and data structures typically focus on adding, deleting and retrieving.
E N D
Implementing Sets/Maps with an Unsorted Array Computer Science 4 Mr. Gerb Reference: Objective: Understand how to implement Maps and Sets using an unsorted array.
Implementing Search • Search algorithms and data structures typically focus on adding, deleting and retrieving. • These are usually the operations with the highest complexity • Size(), clear(), etc. are usually O(1) • So we will focus our study of search implementations on these three operations.
Implementing Sets and Maps using an array list • Simplest implementation: • Store each item in an array list class ArraySet implements set { ArrayList al= new ArrayList(); ... }
Implementing add() • Search through the arrayList one by one. • If you find it, do nothing • If you don’t find it, add it boolean add(Object ob) { int x=0; boolean notFound=false; while (x<al.size()&& !ob.equals(al.get(x))) ++x; if (x>=al.size()) { al.add(ob); notFound=true; } return notFound; }
Implementing contains() • Search through the arrayList one by one. • If you find it, return true • Otherwise, return false • This type of search is called sequential search boolean contains(Object ob) { int x=0; while (x<al.size()&& !ob.equals(al.get(x))) ++x; return (x>=al.size(); }
Implementing remove() • Search through the arrayList one by one. • If you find it, remove it • Otherwise, return false boolean remove(Object ob) { int x=0; boolean removed=false; while (x<al.size()&& !ob.equals(al.get(x))) ++x; if (x<al.size()) { al.remove(x); removed=true; } return removed; }
Efficiency of ArraySet • To add, need to make sure it is not already there. • Will need to search the whole list. • Therefore adding to an ArraySet is O(N) • To find whether something is in the set • Need to search the whole list to conclude it’s not there. • Need to search half the list (on average) to determine it’s already there • Therefore contains is O(N) • To remove • Need to search half the set on average • Need to move the other half down one • Therefore remove is O(N)
Implementing Maps • Maps are no harder to implement than Sets • Instead of storing values, store key/value pairs: • Implement equals() by comparing the key • Return the value if the key is found
Summary • Can implement Set or Map with an ArrayList. • Add searches the list, adds if not found • Get searches the list using sequential search • Remove searches the list, uses the ArrayList remove to move everything down if found. • All three operations using ArrayList run in O(N) time.