Presentation is loading. Please wait.

Presentation is loading. Please wait.

FIT1002 2006 1 Objectives By the end of this lecture, students should: understand iteration over arrays searching and sorting in arrays the differences.

Similar presentations


Presentation on theme: "FIT1002 2006 1 Objectives By the end of this lecture, students should: understand iteration over arrays searching and sorting in arrays the differences."— Presentation transcript:

1 FIT1002 2006 1 Objectives By the end of this lecture, students should: understand iteration over arrays searching and sorting in arrays the differences in efficiency for different types of searching understand how to represent a list in an array understand how to encapsulate a new datatype (here list) with its operations in a class.

2 FIT1002 2006 2 Arrays as Lists An array stores several elements of the same type can be thought of as a list of elements: 13 5 19 10 7 27 17 1 int a[8] 5191072717113

3 FIT1002 2006 3 Lists We require the following operations on lists: 1.adding an element 2.deleting an element 3.finding an element 4.getting the first element (“head”) 5.getting everything but the first element (“rest” or “tail”) We will now construct a class “ListInArray” that implements a list structure by using an array.

4 FIT1002 2006 4 Unsorted List: Add used: 1 ??? 012345 theList ??? Dave we use an array to represent the list the size of this array dictates the maximum list length we need to keep a counter (“used”) of how many array positions are used, ie. valid the counter as well as the array (“theList”) will be instance variables of our “ListInArray” class

5 FIT1002 2006 5 ???Cary Unsorted List: Add (cont) last valid index + 1 Dave??? 012345 used: 2 theList we use an array to represent the list the size of this array dictates the maximum list length we need to keep a counter (“used”) of how many array positions are used, ie. valid the counter as well as the array (“theList”) will be instance variables of our “ListInArray” class

6 FIT1002 2006 6 Class Structure for Lists in Arrays we need to store the elements (array) and the counter for used elements. public class ListInArray { private int[] theList; private int used=0; public ListInArray(int length) { // initialise instance variables theList = new int[length]; for (int i=0; i<length; i++) theList[i] = 0; } public int[] getList() { return (int[]) theList.clone(); } … // methods will follow here // define (as always): toString(), display() }

7 FIT1002 2006 7 Accessor Functions and Privacy Leaks Note that the accessor method for ”theList” does not just return the value of the instance variable. Instead it “clones” the array. This means that it generates a complete new copy of this array and returns it. What would happen otherwise? Consider the code Remember that the contents of the list should only be changed via the interface of “ListInArray”. What happens here? ListInArray l = new ListInArray(5); (l.getList())[3]= 99;

8 FIT1002 2006 8 Accessor Functions and Privacy Leaks As an array variable is a reference type (like an object), the calling procedure would otherwise be able to make changes to the instance variable which we meant to be “private”. This is called a privacy leak. Always return a clone (copy) of array-valued private instance variables. This ensures that the array cannot be changed from outside the object that “owns” this instance variable. Cloning for arrays is a built-in function (.clone()). Cloning for objects has to be implemented by you. Advanced Question (optional): The matter becomes truly tricky if you have arrays containing objects. What we did above is called “shallow cloning”. The technique required now is called “deep cloning”. Can you imagine what deep cloning has to do?

9 FIT1002 2006 9 Adding Elements Recall the algorithms for adding elements: if there is space left in the list { set the element at the index “used” to the new value; increment used counter; return success code (true) } else return error code (false) public boolean add(int elem) { boolean spaceLeft = (used<theList.length); if (spaceLeft) { theList[used] = elem; used ++; } return spaceLeft; }

10 FIT1002 2006 10 Linear Search Problem: determine if an element is present in an array Method: start at one end look at each array element until the sought element is found Also called sequential search

11 FIT1002 2006 11 public boolean searchLin(int elem) { boolean found = false; int i=0; while (!found && i < used) { // stop traversing the // list as soon as // found found |= (theList[i]==elem); i++; } return found; } isPresent (array, val, arraySize) { set integer count to 0 set fboolean ound to false while ( not found and not yet processed all array elements ) { if ( current array element is val ) { set found to true } increment count } return found } Linear Search: Algorithm and Code

12 FIT1002 2006 12 What does Efficiency Mean? Algorithm: a set of instructions describing how to do a task Program: an implementation of an algorithm Complexity theory describes the time and space used by an algorithm The time and space requirements of an algorithm enable us to measure how efficient it is

13 FIT1002 2006 13 Types of Computer Resources Time: elapsed period from start to finish of the execution of an algorithm Space (memory): amount of storage required by an algorithm Hardware: physical mechanisms required for executing an algorithm

14 FIT1002 2006 14 How to Measure Efficiency? Use your watch? Use the computer clock? Not a good idea, because: What if you run your program on different computers? Your program may also wait for I/O or other resources While running a program, a computer performs many other computations Depends on programming/coding skill

15 FIT1002 2006 15 Abstract Notion of Efficiency We are interested in the number of steps executed by an algorithm step  execution of an instruction The running time of an algorithm is proportional to the number of steps executed by the algorithm Running time is given as a function of the size of the input data: “ Big-O Notation ”

16 FIT1002 2006 16 Linear Search Efficiency What is the size of the input data? The size of the array being searched is N What is the time complexity of this algorithm? Each time through the loop we perform 3 operations (negation, comparsion, and) !found && i<used 1 array access, 1 comparison, 1 operation (or), and 1 assignment found = ( found | (theList[i]==elem) ) Total: 7 operations So we execute approximately f(N)=7*N ops.

17 FIT1002 2006 17 Linear Search Efficiency (cont) Best case? Wanted item is at the start of the list 2 (initializations) + 7 operations Worst case? Wanted item is not found 2 + 7N  O(N) Average case? Average of [Wanted item is in position 1, 2, …, N ]

18 FIT1002 2006 18 Big-O Notation Big-O notation is a function of the size of the input Example: Input: N integers Algorithm complexity: Constant O(1) Logarithmic O(log N) Linear O(N) n log(n) O(N log N) Quadratic O(N 2 ) Cubic O(N 3 ) Exponential O(2 N )

19 FIT1002 2006 19 Calculating Complexity: Big-O Notation Simplify and choose the highest term Examples: 2 + 3N + 10N + 3N 2 + 100 = 3N 2 + 13N + 102  O(N 2 ) 40N + N 3  O(N 3 ) 25  O(1)

20 FIT1002 2006 20 Binary Search Can we do any better than linear search? Example: How do you find a word in the dictionary, or a number in the phone directory? Assume that the array is sorted and use bisection

21 FIT1002 2006 21 Binary Search (cont) If ( value == middle element ) value is found else if ( value < middle element ) search left-half of list with the same method else search right-half of list with the same method

22 FIT1002 2006 22 Case 1: val == a[mid] val = 10 low = 0, high = 8 57910131719127 123456708 a: lowhigh Binary Search -- Example 1 mid mid = (0 + 8) / 2 = 4 10

23 FIT1002 2006 23 Case 2: val > a[mid] val = 19 low = 0, high = 8 mid = (0 + 8) / 2 = 4 Binary Search -- Example 2 579101 13171927 123456708 a: mid lowhigh new low new low = mid + 1 = 5 13171927

24 FIT1002 2006 24 Case 3: val < a[mid] val = 7 low = 0, high = 8 mid = (0 + 8) / 2 = 4 Binary Search -- Example 3 10131719 5791 27 123456708 a: mid lowhigh new high new high = mid - 1 = 3 5791

25 FIT1002 2006 25 val = 7 Binary Search -- Example 3 (cont) 57910131719127 123456708 a: 57910131719127 123456708 a: 57910131719127 123456708 a:

26 FIT1002 2006 26 public boolean searchBin(int elem) { boolean found = false; int low=0, high=used-1; while (!found && low <= high) { // if not found the indices // will "cross over" int mid = (low+high)/2; if (theList[mid]==elem) found = true; else if (theList[mid] < elem) low = mid+1; else high = mid-1; } return found; } isPresent (array, val, arraySize) { set low to first array position set high to last array position set found to false; while ( not found and low < = high ) { set mid to half of low + high if (array element in mid is val ) { set found to true } else if ( middle value < val ) { set low to mid + 1 } else { set high to mid - 1 } return found } Binary Search -- Algorithm and Code

27 FIT1002 2006 27 How would you modify the program so that it returns the position of the sought item (i.e., findPosition rather than isPresent )? How would you indicate “not found”? Binary Search -- Exercise

28 FIT1002 2006 28 Return the current index when found Return an impossible index (eg -1) if not found. public int findIndex(int elem) { boolean found = false; int low=0, high=used-1; int mid=0; while (!found && low <= high) { // if not found the indexes will "cross over" mid = (low+high)/2; if (theList[mid]==elem) found = true; else if (theList[mid] < elem) low = mid+1; else high = mid-1; } if (found) return mid; else return -1; } Binary Search -- Exercise

29 FIT1002 2006 29 Binary Search Efficiency What is the size of the input data? The size of the array being searched is N What is the time complexity of this algorithm? Each time through the loop (without finding) we perform 2 array access 3 comparisons 5 arithmetic and boolean operations 2 assignments Total: 12 operations

30 FIT1002 2006 30 Best case? item is in the middle 3+12 operations  O(1) Worst case? item is not found 12  log 2 N operations  O(log 2 N) Average case? O(log 2 N) Binary Search Efficiency (cont)

31 FIT1002 2006 31 Calculating the Worst Case Complexity After 1 bisectionN/2 items After 2 bisectionsN/4 = N/2 2 items... After i bisectionsN/2 i = 1 item i = log 2 N

32 FIT1002 2006 32 Exercise Problem: Implement search over an array of objects, e.g. persons? Method: 1.Use the “Person” class you encountered earlier. Use linear search. Search for a particular name. 2.For binary search the array must be sorted. Assume that the “Person”s are sorted by name. You need to use the method “compareTo” in the class “String” to compare Strings lexicographically (see Java API documentation).

33 FIT1002 2006 33 Notes on Searching Linear search can be done on any (sorted or unsorted) list, but it is inefficient Binary search requires a list to be sorted is more efficient Sorting a list: later

34 FIT1002 2006 34 Sorted Lists As we have seen that we may require a list in sorted form, we’d better create an insert method that allows us maintain the sorted order of a list. We can use the same class structure as before, we just need to insert in the right positions.

35 FIT1002 2006 35 Empty Sorted List 012345 ??? used: 0 theList public class ListInArray { private int[] theList; private int used=0; …

36 FIT1002 2006 36 Dave Sorted List: Add Sorted Case 1: List is empty same as unsorted ??? 012345 used: 1 theList Example: add sorted “Dave”

37 FIT1002 2006 37 Case 2: List is not empty find correct position Dave??? 012345 used: 1 theList Example: add sorted “Abe” Sorted List: Add Sorted

38 FIT1002 2006 38 Case 2: List is not empty find correct position make room by moving all items to the right Dave??? 012345 used: 1 theList Example: add sorted “Abe” Sorted List: Add Sorted

39 FIT1002 2006 39 Case 2: List is not empty find correct position make room by moving all items to the right put item in that position AbeDave??? 012345 used: 1 theList Example: add sorted “Abe” Sorted List: Add Sorted

40 FIT1002 2006 40 Case 2: List is not empty find correct position make room by moving all to the right put item in that position update “used” count AbeDave??? 012345 used: 2 theList Example: add sorted “Abe” Sorted List: Add Sorted

41 FIT1002 2006 41 Case 2: List is not empty AbeCaryDaveEd??? 012345 used: 4 theList Example: add sorted “Arnie” Sorted List: Add Sorted

42 FIT1002 2006 42 Case 2: List is not empty AbeCaryDaveEd??? 012345 used: 4 theList Example: add sorted “Arnie” Sorted List: Add Sorted

43 FIT1002 2006 43 Case 2: List is not empty AbeArnieCaryDaveEd??? 012345 used: 5 theLIst alphabetical ordering is maintained Example: add sorted “Arnie” Sorted List: Add Sorted

44 FIT1002 2006 44 Case 2: List is not empty AbeArnieCaryDaveEd??? 012345 used: 5 theList What if the array is already full? Sorted List: Add Sorted

45 FIT1002 2006 45 Algorithm addSorted boolean addSorted(elem) { set successcode = true if space is left set I to first index if list is not full { while (end of used array not reached and theList[i]<= elem) increment i; for (j from last used index down to i) shift element at index j-1 one position up insert elem in the empty spot of array update used counter } return successcode }

46 FIT1002 2006 46 Method addSorted public boolean addSorted(int elem) { boolean spaceLeft = (used<theList.length); if (spaceLeft) { int i = 0; while(i<used && theList[i]<=elem) i++; for (int j=used; j>i; j--) theList[j] = theList[j-1]; theList[i]=elem; used++; } return spaceLeft; }

47 FIT1002 2006 47 List: Delete an Element Same for both sorted and unsorted lists Algorithm: find the position of the item to be deleted linear or binary search if found move all items one position to the left decrement count Special cases: list is empty item not found

48 FIT1002 2006 48 List: Delete an Element AbeArnieCaryDaveEd??? 012345 used: 5 theList Example: delete “Cary” - find the position of the element

49 FIT1002 2006 49 List: Delete an Element AbeArnieDaveEd??? 012345 used: 5 theList Example: delete “Cary” - find the position of the element - remove the element

50 FIT1002 2006 50 Dave List: Delete an Element AbeArnieDaveEd ??? 012345 used: 5 theList Example: delete “Cary” - find the position of the element - remove the element - shuffle the items after the deleted item to the left We don’t need to actually clear this. Just update used

51 FIT1002 2006 51 List: Delete an Element AbeArnieDaveEd ??? 012345 used: 4 theList Example: delete “Cary” - find the position of the element - remove the element - shuffle the items after the deleted item to the left - decrement “used” count

52 FIT1002 2006 52 List: Delete an Element (Java) public boolean delete(int elem) { int index=findIndex(elem); if (index>=0) for (int i=index; i<(used-1); i++) theList[i]=theList[i+1]; if (index>=0) used--; return (index>=0); }

53 FIT1002 2006 53 Inheritance between List Types Very Advanced Exercise (strictly optional): We have defined sorted and unsorted lists in the same class. In true object-oriented style we should probably have defined one as an extension (subclass) of the other. Which would you choose as the superclass and why? Somewhat counter-intuitively, Sorted List must be the superclass. This is because it must contain the searchBin method, and this method relies on the list being sorted, so SortedList must not have access to unsorted insertion. Alternatively, you could make SortedList the sub-class, but then you would have to override the unsorted insertion method by sorted insertion in this sub-class. Try to re-define the two types of lists by using inheritance as depicted below. This will take you on a little adventure through a number of advanced topics that we do not have the time to touch upon: typecasting, cloning, superclass constructors, etc. Study these topics in Savitch as you need them or ask the instructor if you encounter problems. Warning: only try this if you are eager to put a considerable amount of extra effort in.

54 FIT1002 2006 54 ArrayLists in Java Advanced and optional (self-guided study recommendation): Luckily, you don’t have to implement this yourself. As “flexible Arrays” (i.e. arrays that can grow and shrink) are quite commonly needed, they are provided in Java as a standard class. called “ArrayLists”. These combine the advantages of Arrays (access by index) and lists. To learn the details of ArrayLists check their definition in the Java API. If you know the size of the array in advance, you should always use a normal array, as these are more efficient. An important point about ArrayLists is that they use so-called Generics. We cannot go into details here, and will just loosely say that a generic class is a class that is “parameterized” by a base type (here: the type of the elements of the list). The class behaves always in the same way, but can be used with different base types (see following code example). This base type is provided in angled brackets after the generic class name. For example, the type ArrayList is an Array List with Strings as elements, whereas the class ArrayList is an Array List with Person as the element class. Warning: You will not only have to learn about Generics, but also about Wrapper Classes.

55 FIT1002 2006 55 Reading Savitch, Chapter 6 – for ArrayLists (strictly optional): Savitch, Chapter 14 and Savitch, pp 267-273 (wrapper classes)


Download ppt "FIT1002 2006 1 Objectives By the end of this lecture, students should: understand iteration over arrays searching and sorting in arrays the differences."

Similar presentations


Ads by Google