Linear Search Java Code
1 int[] data;
2 int size;
3
4 public boolean linearSearch(int key)
5 {
6 int index = 0;
7 while(index < size) {
8 if(data[index] == key) {
9 return true;
10 }
11 if(data[index] < key)) {
12 return false;
13 }
14 index++;
15 }
16 return false;
17 }
Explanation:
- line 1: tells us that we have an array of integers called
data. An array is just an ordered list of values, just
like the list we talked about in our algorithm. An integer is a
positive or negative whole number.
- line 2: size tells us the number of items that we have in the
list.
- lines 4, 5, and 17: These lines tell us that the code between line 5
and 17 performs one task, and give the name linearSearch
to the task. key is the target item that we will search
for in data. The word boolean tells us that
linearSearch will return true if it finds the key
in the list, and it will return false if the key is not in
the list.
- line 6: index is the variable we will use to get the next
item in the list, so we will give it an initial value of 0.
- line 7: This line says that we will keep repeating the lines between 7
and 15 as long as index < size
- line 8, 9, 10: if we have found our key, then we return true
- line 11, 12, 13: if the item in the list has a smaller value than our
key, we know the key cannot be in the list so we return false.
- line 14: We add one to index which lets us look at the next item in
the list.
Karen Reid
Last modified: Thu Mar 2 17:28:56 EST 2000