Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall 645-4739

Similar presentations


Presentation on theme: "CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall 645-4739"— Presentation transcript:

1 CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall 645-4739 alphonce@buffalo.edu

2 Exam 3 Monday (12/5) Exam 3 review Wednesday (12/7) Exam 3 Friday (12/9) Final exam review

3 This week Linear and binary search Friday – maybe lab 8 discussion

4 Goal: determine whether a target item is in a given collection. Use ArrayList for examples for now. In 116 we’ll see how to write a more general solution (one that’s not only for Integers). Search

5 ArrayList Allows for efficient index operations get(int index) method returns the value at the specified index

6 Linear search Search for target value starting at index 0, continuing to index size()-1 public boolean linearSearch(ArrayList list, Integer target) { for (int i=0; i<list.size(); i=i+1) { if (target.equals(list.get(i))) { return true; } return false; }

7 An example of a linear search for 79. Starting at index 0, the target value (79) is compared to the value at each index. Each row in the table denotes a different stage in the search; the top row (under the “index” row) shows the sequence of values prior to starting the search. Each subsequent row shows the values removed from consideration (shaded) at each iteration of the algorithm. index 0index 1index 2index 3index 4index 5index 6index 7 37121723253954 37121723253954 37121723253954 37121723253954 37121723253954 37121723253954 37121723253954 37121723253954 37121723253954

8 Binary search (assume data is sorted, smallest to largest) Search for target value starting at middle index; search in left or right partition based on result of comparison. public boolean binarySearch(ArrayList list, Integer target) { int L = 0; int R = list.size(); int M; while ( L != R ) { M = (L+R)/2; if ( target.equals(list.get(M)) ) { return true; } if ( target.intValue() < list.get(M).intValue() ) { R = M; } else { L = M+1; } } return false; }

9 An example of a binary search for 24. Starting at middle index, the target value (79) is compared to the value stored there. Each row in the table denotes a different stage in the search; the top row (under the “index” row) shows the sequence of values prior to starting the search. Each subsequent row shows the values removed from consideration (shaded) at each iteration of the algorithm. index 0index 1index 2index 3index 4index 5index 6index 7 37121723253954 37121723253954 37121723253954 37121723253954


Download ppt "CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall 645-4739"

Similar presentations


Ads by Google