Вы находитесь на странице: 1из 8

Searching

Searching is an issue, which often is to be dealt with in programming.


This paper gives some examples of searching algorithms using various data structures. The
examples can easily be changed to deal with other data structures or other requirements.

1 Linear search
1.1 Linear search in an array
The following example shows a method doing linear search in an array of integers. The method
uses a while loop:
/**
Returns true, if target is found in arr.
*/
public boolean linearSearchArray(int[] arr, int target){
boolean found = false;
int i = 0;
while (!found && i < arr.length){
int k = arr[i];
if (k == target)
found = true;
i++;
}
return found;
}
The algorithm can be illustrated as
0

arr.length-1

arr

i
Where the blue illustrates the elements, we have been searching so far, without finding what we are
looking for. The white part is the elements we have not checked yet. The variable i is pointing at the
element we are checking at the moment.
The method returns a boolean, indicating whether target was found among the values in the
array. Please observe that the loop stops, when the element being searched for is found in the array,
as there is no reason to continue the search.

The same method can be programmed with a for loop::


/** Returns true, if target is found in arr.
*/
public boolean linearSearchArray(int[] arr, int target){
boolean found = false;
for (int i = 0; !found && i < arr.length; i++){
int k = arr[i];
if (k == target)
found = true;
}
return found;

}
Normally, it is not satisfactory just to know, whether the target exists in the array. We want to
know the index of the target in the array. If that is the case, we must change the method to:
/** Returns the index of target in arr.
If target is not found, -1 is returned.
*/
public int linearSearchArray(int[] arr, int target){
int index = -1;
boolean found = false;
int i = 0;
while (!found && i < arr.length){
int k = arr[i];
if (k == target) {
index = i;
found = true;
}
i++;
}
return index;
}

1.2 Linear search in an ArrayList of strings


If the array is replaced by an ArrayList<String> the code must be modified, as we cannot compare
Strings using ==. Instead we have to use the equals() method in the String class:
/** Returns the index of target in list.
If target is not found, -1 is returned.
*/
public int linearSearchList(ArrayList<String> list,
String target){
int index = -1;
boolean found = false;
int i = 0;
while (!found && i < list.size()){
String k = list.get(i);
if (k.equals(target)) {
index = i;
found = true;
}
i++;
}
return index;
}

1.3 Linear search in an ArrayList of Customer objects


In this example we show how to search in an ArrayList<Customer>.
The Customer class is defined as:
public class Customer {
private String name;
private int no;
public Customer(String name, int no) {
this.name = name;
this.no = no;
}
public String getName() {
return name;
}
//other getters and setters
}

Here is the search method:


/** Returns the customer named name in list.
If such a customer is not found, null is returned.
*/
public Customer linearSearchList(ArrayList<Customer> list,
String name){
Customer customer = null;
boolean found = false;
int i = 0;
while (!found && i < list.size()){
Customer cust = list.get(i);
if (cust.getName().equals(name)) {
customer = cust;
found = true;
}
i++;
}
return customer;
}
If more than one Customer with name name exists in the list, the first of these is returned.

1.4 Linear search with more complicated matching


In a more complicated situation, the matching is not as simple as: if (k==target)
As an example, lets look at an algorithm, which search for a substring m in another string sm.
If sm is "happy holiday" and m is "holi", m is found at index 6 in the string sm.
The search algorithm could then be:
public int SearchSubString(String sm, String m) {
int index = -1;
boolean found = false;
int i = 0;
while (!found && i <= sm.length m.length()) {
if (match(i, ...)) [ //parameters have to be filled in
index = i;
found = true;
}
i++;
}
return index;
}

If sm has the length 13 (as in happy holiday) and m has length 4 (as in holi) then the last index i
in the string to use is 13 - 4 = 9. If i = 9, then holi is trying to match the indexes 9,10,11 and 12,
and 12 is exactly the last index of sm.
All the complicated matching is encapsulated in the method match(). The match() is being made
from index i in sm. The method match() must also know the two strings sm and m.
The method call must therefore be
match(i,sm, m);
A match is found, if
m[j] = sm[i+j] for all j in [0..length(m)-1]
The task remaining is writing the match() method.

Figure: string matching.


When we are matching sm from position i with m, we are matching
sm[i] == m[0]
sm[i+1] == m[1]
sm[i+2] == m[2]

sm[i+ m.length-1] == m[m.length-1]

If match() finds one character that is not matching, we can stop, because then the substring m is not
in sm starting with index i. Therefore, we search for the first not matching character.
/**
* Returns whether m occurs as substring in sm from index i.
* Req: i <= sm.length() m.length().
*/
public boolean match(int i, String sm, String m) {
boolean found = false;
int j = 0;
while (!found && j < m.length()){
if (m.charAt(j) != sm.charAt(i+j))
found = true;
j++;
}
return !found;
}
Please note that match is true, if we have NOT found a position, where sm and m differs.

Binary search
2.1 Binary search in a sorted array of String
In this example we show a binary search in an array of integers. A binary search requires that the
data searched in is sorted.
The principle in binary search is to look first at the element in the middle of the array. If this
element is equal to the target, the index of this element is returned. If the element in the middle
is greater than target, the search continues in the left half of the array. If the element in the
middle is smaller than target, the search continues in the right half of the array.
We use two int-variables left and right to define the interval, we want to search.
0

arr.length-1

arr

left

right

/** Returns the index of target in arr.


* If target is not found in arr, -1 is returned.
* Requires: arr is sorted in ascending order.
*/
public int binarySearchArray(int[] arr, int target){
int index = -1;
boolean found = false;
int left = 0;
int right = arr.length-1;
while (!found && left <=right){
int middle = (left+right)/2;
int k = arr[middle]; //k is the middle element
if (k == target) {
index = middle; //target is found
found = true;
}
else if (k > target){
right = middle - 1; //target could be in left part
}
else {
left = middle + 1; //target could be in right part
}
}
return index;
}

If the value of target exists more than once in the array, the above method does not necessarily find
the value with the smallest index.
If we are searching for 5 in the array [2,5,5,5,10,12,20,28,28,30,36,50,54,60,72] the last 5 is found;
but if we are searching for 5 in the array [2,5,5,5,10,12,20,28,28] the first 5 is found.

2.2 Binary search in a sorted ArrayList of Customer objects


In the following example we make the same search as in 1.3. We suppose the ArrayList is sorted
by the name of the customers. As strings are to be compared we have to use the compareTo()
method.
/**
* Returns the customer named name in list.
* If such a customer is not found, null is returned.
* Requires: list is sorted in ascending order.
*/
public Customer binarySearchCustomer(ArrayList<Customer> list,
String name){
Customer customer = null;
boolean found = false;
int left = 0;
int right = list.size()-1;
while (!found && left <=right) {
int middle = (left+right)/2;
Customer cust = list.get(middle);
int comp = cust.getName().compareTo(name);
if (comp == 0) {
customer = cust;
found = true;
}
else if (comp > 0) {
right = middle - 1;
}
else {
left = middle + 1;
}
}
return customer;
}

Вам также может понравиться