1 / 61

Array-Based Lists: Basics and Operations

Learn about the list abstraction, array-based lists, sorting, searching, and implementing a list class in Java.

wendym
Download Presentation

Array-Based Lists: Basics and Operations

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 11 • Array-Based Lists

  2. Knowledge Goals • Understand the list abstraction and basic list operations • Recognize the difference between an array and a list • Understand how to use an array to represent a list • Know how to use a key to establish the order of a sorted list • Understand the principle of "divide and conquer" as expressed in the binary search algorithm

  3. Skill Goals • Add an item to a list • Remove an item from a list • Search for an item in a list • Sort the items in a list into ascending or descending order • Build a list in sorted order • Search for an item in a sorted list using a linear search

  4. Skill Goals • Search for an item using a binary search • Define a class that extends a Java interface • Use Java's Comparable interface • Use ArrayList from the Java library

  5. What is a List? • List • A homogeneouscollection of elements, with a linear relationship between the elements • Linear relationship • Every element (except the first) has a unique predecessor, and every element (except the last) has a unique successor • Length (size in Java) • The number of items in a list; it can vary over time

  6. What is a List? Key Key Sorted list: The predecessor and successor relation- ships are determined by the content of the keys

  7. What is a List? We are concerned only with unique keys

  8. A List Class • Can you name some of the operations that must be applied to a List?

  9. A List Class

  10. A List Class • Transformers • add • remove • Observers • isEmpty • isFull • size • contains • hasNext • Iterators • resetList • next change state observe state process components

  11. A List Class • Attributes • numItems • listItems[0] • . . . • listItems[listItems.length-1] • currentPos number of elements in list array of list elements used by iterator

  12. A List Class

  13. A List Class Class ListOfStrings is unsorted UNSORTED LIST Elements are placed into the list in no particular order with respect to their content SORTED LIST List elements are in an order that is sorted by the content of their keys -- either numerically or alphabetically

  14. A List Class • public ListOfStrings() • { • numItems = 0; • listItems = new String[100]; • currentPos = 0; • } • public ListOfStrings(int maxItems) • { • numItems = 0; • listItems = new String[maxItems]; • currentPos = 0; • } constructors

  15. A List Class • public boolean isEmpty() • { • return (numItems == 0) • } • public int size() • { • return numItems; • } • public boolean isFull() • { • return (numItems == listItems.length); • } observers

  16. A List Class • public boolean contains(String item) • { • int index = 0; • while (index < numItems && • listItems[index].compareTo(item) != 0) • index++; • return (index < numItems); • } See why this works?

  17. item 63 Add: Does it matter where we put the item? Place the item in numItems location and increment numItems numItems 3 listItems[ 0 ] 15 [ 1 ] 39 [ 2 ] -90 [ 3 ] . . . [ listItems.length-1 ]

  18. item 64 After Inserting 64 into an Unsorted List numItems 4 listItems [ 0 ] 15 [ 1 ] 39 [ 2 ] -90 [ 3 ] 64 . . . [ listItems.length-1 ]

  19. A List Class • public void add(String item) • // Result: If the list is not full, puts item as • // the last position in the list; otherwise list • // is unchanged • { • if (!isFull()) • { • listItems[numItems] = item; • numItems++; • } • }

  20. A List class • remove(item) • Search (item, found, index) • if (found) • Shift remainder of list up • Decrement numItems Remove is more difficult ShiftUp for count going from index downTo numItems Set listItems[count] to listItems[count+1]

  21. Can you walk through deleting 39? numItems 4 listItems[ 0 ] 15 [ 1 ] 39 [ 2 ] -90 [ 3 ] 64 . . . [ listItems.length-1 ]

  22. The List Class • public void remove(String item) • { • int index = 0; • boolean found = false; • while (index < numItems && !found) • { • if (listItems[index].compareTo(item) == 0) • found = true; • else • index++; • } • if (found) • { • for (int count = index; count < numItems - 1; • count++) • listItems[count] = listItems[count + 1]; • numItems--; • } • }

  23. A List Class • public void resetList() { currentPos = 0; } • public boolean hasNext() { return (currentPos != numItems); } • public String next() • // Returns the item at the currentPos position • // Assumptions: No transformers are called during the • // iteration { String next = listItems[currentPos]; currentPos++; return next; } Read documentation carefully!

  24. A List Class How are CRC cards and UML diagrams alike? How are they different?

  25. A List Class • A class is not complete until • it has been tested! • Command-driven test driver • A driver program that reads in commands and executes them; an excellent vehicle for unit testing a class • enum Operations {ADD, REMOVE, SIZE, ISEMPTY, ISFULL, CONTAINS, PRINT, QUIT}

  26. A List Class • Main • Read file into list • Set operation to inOperation() • Set keepGoing to true • while (keepGoing) • Execute operation • Set operation to inOperation • Write list to file A command- driven testing program

  27. A List Class • executeOperation • switch(operation) • case ADD: // execute add • case REMOVE: // execute remove • case SIZE: // execute size • case ISEMPTY: // execute isEmpty • case ISFULL: // execute isFull • case CONAINS: // execute contains • case PRINT: // print list • case QUIT: // quit How are resetList, hasNext, and next tested ?

  28. ListWithSort • Sorting • Arranging the components of a list into order

  29. ListWithSort • Straight selection sort • Examine the entire list to select the smallest element • Swap that element with first element (with array index 0) • Examine the remaining list to select the smallest element from it • Swap that element with second element (array index 1) • Continue process until only 2 items remain • Examine the last 2 remaining list elements to select the smallest one • Swap that element with the other

  30. ListWithSort

  31. ListWithSort Can you use the same test driver ?

  32. A Sorted List • Is ListWithSort the same as a SortedList? • Are the same operations needed for a List and a SortedList? Any extra ones needed? • From the client's (user's) point of view, what is the visible difference between an unsorted list and a sorted list?

  33. A Sorted List

  34. A Sorted List Add

  35. A Sorted List • public void add(String item) • { • if (! isFull()) • {// find proper location for new element • int index = numItems - 1; • while (index >= 0 && • item.compareTo(listItems[index]) < 0) • { • listItems[index + 1] = listItems[index]; • index--; • } • listItems[index +1] = item; // insert item • numItems++; } • }

  36. A Sorted List remove and next must maintain order but they already do!

  37. Searching • Linear (sequential) search • Search begins at the beginning of the list and continues until the item is found or the entire list has been searched • Can searching be improved if the items are in sorted order?

  38. Searching How many comparisons are needed to find 11? 67? 2? 100? How many comparisons are needed to find 11? 67? 2? 100? That's better, but we can do better yet

  39. Searching • Binary search(list must be sorted) • Search begins at the middle and finds the item or eliminates half of the unexamined items; process is repeated on the half where the item might be Say that again…

  40. Searching

  41. Searching Boolean Binary Search (first, last) If (first > last) return false Else Set middle to (first + last)/2 Set result to item.compareTo(list[middle]) If (result is equal to 0) return true Else If (result < 0) Binary Search (first, middle - 1) Else Binary Search (middle + 1, last)

  42. Searching Searching for "bat"

  43. Searching

  44. Searching • public boolean isThere(String item) • // Assumption: List items are in ascending order • // Returns true if item is in the list; false otherwise • { int first = 0; int last = numItems - 1; • int middle; boolean found = false; • while (last >= first && !found) • { • middle = (first + last) / 2; • if (item.compareTo(listItems[middle]) == 0) • found = true; // Item has been found • else • if (item.compareTo(listItems[middle] < 0) • last = middle - 1; // Look in first half • else first = middle + 1; // Look in second half • } • return found; • }

  45. Searching Average Number of iterations Is a binary search always better?

  46. Refactoring the List Hierarchy Refactoring Modifying code to improve its quality without changing is functionality There is a better way!

  47. Refactoring the List Hierarchy public abstract class AbstractList { public AbstractList() public AbstractList(int maxItems) public boolean isFull() public boolean isEmpty() public int size() public void resetList() public boolean hasNext() public String next() public boolean contains(String item) public abstract void remove(String item) public abstract void add(String item) } What about contains?

  48. Refactoring the List Hierarchy

  49. List of Comparable Objects Wouldn't it be nice if we could have one abstract class for any data type, not one for each type of item that could be on the list? You can if you declare the type of the items to be Comparable protected Comparable[] listItems

More Related