Download Lecture 3

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Lecture 3
Linear Search and Binary Search
ArrayLists
CS 202
John Hurley
Write and Test Your Code Incrementally
You should be able to explain in one sentence how any method
you write works. If you can’t, break it down into two or more
methods.
The Stevie Wonder principle:
"When you believe in things that you
don't understand, then you suffer."
2
Lists



Need to import java.util.List as well as whatever specific
type of list you use, eg java.util.ArrayList
A List must be a list of values of some other data type, in
the same way that an array is an array of items of some
other type. List are parameterized by the data type of the
values in the list.
Unlike an array, a list can only contain objects, not primitive
types. For example, you can not declare a list of doubles, but
you can declare a list of Doubles. You will understand this
better in a couple of weeks.
We show the underlying data type by enclosing it in angle
braces, for example:

List <String>
List Methods

The List class provides many methods you will
need to use with lists. Here are some easy to
understand ones.
–
add() adds an item to the end of the list
–
get(int position) gets a reference to the item at
the specified position in the list
–
isEmpty() returns a boolean that indicates just
what it sounds like
–
size() shows the number of items in the list
–
clear() deletes all items from the list
package demos;
import java.util.List;
import java.util.ArrayList;
public class Demo {
public static void main(String args[]) {
// create the list
List<String> myList = new ArrayList<String>();
// add items to the list
myList.add("Andy");
myList.add("Barry");
myList.add("Cathy");
// print the items in the list
for(String s: myList)
System.out.println(s);
System.out.println();
// add another item to the list, then print
myList.add("Doug");
for(String s: myList)
System.out.println(s);
System.out.println();
// delete an item from the list, then print
myList.remove(0);
for(String s: myList)
System.out.println(s);
} // end main()
}
More List Methods
More List Methods
Some List methods hinge on the fact that a List contains
elements of some other data type.



contains(Object o)
indexOf(Object o) finds the index of the first occurrence of a
value in the list
lastIndexOf(Object o) finds the index of the last occurrence
of a value in the list
More List Methods
public static void main(String args[]) {
List<Double> myList = new ArrayList<Double>();
List<Double> testList = new ArrayList<Double>();
final double PI = 3.14159;
double fToCFactor = 5.0/9.0;
double bodyTemperature = 98.6;
myList.add(PI);
myList.add(fToCFactor);
MyList.add(PI);
testList.add(PI);
testList.add(fToCFactor);
testList.add(bodyTemperature);
for(Double d: testList)
System.out.println(myList.contains(d)?("The first occurrence of " + d + " in
myList is at position "+ myList.indexOf(d) +
" and the last occurrence is at
"myList does not contain " + d);
} // end main()
" + myList.lastIndexOf(d)):
Searching Arrays and Lists
Searching is the process of looking for a specific
element in a data structure; for example, discovering
whether a certain score is included in a list of scores.
Searching is a common task in programming. There are
many algorithms and data structures devoted to
searching. In this section, two commonly used
approaches are discussed, linear search and binary
search.
public class LinearSearch {
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
[0] [1] [2] …
if (key == list[i])
return i;
list
return -1;
key Compare key with list[i] for i = 0, 1, …
}
}
10
Linear Search
The linear search approach compares the key
element, key, sequentially with each element in
an array or list. The method continues to do so
until the key matches an element in the list or
the list is exhausted without a match being
found.
If a match is made, the linear search returns the
index of the element that matches the key. If no
match is found, the search returns -1.
11
animation
Linear Search Animation
Key
List
3
6 4 1 9 7 3 2 8
3
6 4 1 9 7 3 2 8
3
6 4 1 9 7 3 2 8
3
6 4 1 9 7 3 2 8
3
6 4 1 9 7 3 2 8
3
6 4 1 9 7 3 2 8
12
From Idea to Solution
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
if (key == list[i])
return i;
return -1;
}
Trace the method
int[]
int i
int j
int k
list = {1, 4, 4, 2, 5, -3, 6, 2};
= linearSearch(list, 4); // returns 1
= linearSearch(list, -4); // returns -1
= linearSearch(list, -3); // returns 5
13
Binary Search
For binary search to work, the elements in the
array must already be ordered. Without loss of
generality, assume that the array is in ascending
order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key with
the element in the middle of the array.
14
Binary Search, cont.
Consider the following three cases:
If the key is less than the middle element, you
only need to search the key in the first half of
the array.
If the key is equal to the middle element, the
search ends with a match.
If the key is greater than the middle element,
you only need to search the key in the
second half of the array.
15
animation
Binary Search
Key
List
8
1 2 3 4 6 7 8 9
8
1 2 3 4 6 7 8 9
8
1 2 3 4 6 7 8 9
16
Binary Search, cont.
key is 11
low
key < 50
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list
2
low
key > 7
mid
4
high
7 10 11 45 50 59 60 66 69 70 79
mid
high
[0] [1] [2] [3] [4] [5]
list 2 4 7 10 11 45
low
mid
high
[3] [4] [5]
key == 11
list
10 11 45
17
key is 54
low
Binary
Search,midcont.
high
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key > 50
list
2
4 7 10 11 45
50 59 60 66 69 70 79
low
key < 66
mid
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list
59 60 66 69 70 79
low mid
high
[7] [8]
key < 59
high
list
59 60
low
high
[6] [7] [8]
59 60
18
Binary Search, cont.
The binarySearch method returns the index of the
element in the list that matches the search key if it is
contained in the list. Otherwise, it returns
-insertion point - 1.
The insertion point is the point at which the key
would be inserted into the list.
19
From Idea to Soluton
/** Use binary search to find the key in the list */
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
20
The Arrays.binarySearch Method
Since binary search is frequently used in programming, Java provides
several overloaded binarySearch methods for searching a key in an array of
int, double, char, short, long, and float in the java.util.Arrays class. For
example, the following code searches the keys in an array of numbers and
an array of characters.
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println("Index is " +
Return is 4
java.util.Arrays.binarySearch(list, 11));
char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};
System.out.println("Index is " +
Return is –4 (insertion point is
3, so return is -3-1)
java.util.Arrays.binarySearch(chars, 't'));
For the binarySearch method to work, the array must be pre-sorted in
increasing order.
21
The Arrays.sort Method
Since sorting is frequently used in programming, Java provides several
overloaded sort methods for sorting an array of int, double, char, short,
long, and float in the java.util.Arrays class. For example, the following
code sorts an array of numbers and an array of characters.
double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};
java.util.Arrays.sort(numbers);
char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};
java.util.Arrays.sort(chars);
The sort algorithm used depends on the parameter type
22
import javax.swing.JOptionPane;
Age Guess
public class BetterGuess {
public static void main(String[] args) {
int tries = 0;
int high = 100;
int low = 0;
int guess;
int direction;
do {
guess = (high + low) / 2;
String[] choices = { "Older", "This Old", "Younger" };
direction = JOptionPane.showOptionDialog(null, "Are you " + guess + "?", "Age Guess",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, "Age Guess");
if (direction == 0)
low = guess + 1; // last guess was too low
if (direction == 2)
high = guess - 1; // last guess was too high
tries++;
} while (direction != 1);
System.out.println("Guessed in " + tries + " tries");
}
}
23
Menu with Loop And Switch
It is very common for an application to give a user a menu of options within a loop that continues
until the user chooses to quit:
public class MenuLoopDemo {
public static void main(String[] args){
MenuLoopDemo d = new MenuLoopDemo();
d.menu();
}
public void menu(){
int choice = 0;
String[] options = {"Quit", "EasyA", "Swift Kick"};
do{
choice = JOptionPane.showOptionDialog(null, "Choose One", "Please Select One", 2, choice, null, options, options);
switch(choice){
case 1: easyA();
break;
case 2: swiftKick();
break;
}
} while(choice != 0);
}
public void easyA(){
System.out.println("Easy A");
}
public void swiftKick(){
System.out.println("Swift Kick!");
}
}
24