Date post: | 22-Dec-2015 |
Category: |
Documents |
View: | 217 times |
Download: | 0 times |
2
Chapter ContentsThe ProblemSearching an Unsorted Array
• Iterative Sequential Search• Recursive Sequential Search• Efficiency of Sequential Search
Searching a Sorted Array• Sequential search• Binary Search• Java Class Library: the Method binarySearch
Searching an Unsorted Chain• Iterative Sequential Search• Recursive Sequential Search• Efficiency of Sequential Search of a Chain
Searching a Sorted Chain• Sequential Search• Binary Search
Choosing a Search Method
3
The Problem
Searching is an every day occurrence.
Searching a particular item among a collection of many items
4
Searching Strategies
The sequential search• Apply to both unsorted ADT list and sorted
ADT list
The binary search• Sorted ADT list implemented by array • Faster than a sequential search• Sorting usually takes much more time than
searching
5
Iteratively Search an Unsorted ArrayA method that uses a loop to search an array. Return is boolean type.
Compare target entry with each entry until locate the target or look at all entries
public boolean contains(Object anEntry)
{ boolean found = false;for (int index = 0; !found && (index < length); index++){ if (anEntry.equals(entry[index]))
found = true;} // end forreturn found;
} // end contains
6
Searching an Unsorted Array
Example of two outcomes: An iterative sequential search of an array that (a) finds its target; (b) does
not find its target
7
Recursively Search an Unsorted ArrayLook at the first entry. If that entry is the desired one, we end the search. Otherwise we search the rest of the array( an identical but smaller problem). Base case is an empty array and return false.A recursive algorithm to search an array as a private method for class listAlgorithm to search list[first] through list[last] for desiredItemprivate boolean Search( T desiredItem, int first, int last)
{
if (there are no elements to search: first > last)return false
else if (desiredItem equals list[first])return true
elsereturn the result of searching list[first+1] through
list[last] by calling Search (desiredItem, first+1, last);
}
8
Searching an Unsorted Array
A recursive sequential search of an array that (a) finds its target;
(b) does not find its target.
9
Efficiency of a Sequential Search
Best case O(1)• Locate desired item first
Worst case O(n)• Must look at all the items
Average case O(n)• Must look at half the items • O(n/2) is still O(n)
Easy to understand and implement sequential search algorithm. However, if problem size is big, it is time consuming.
10
Searching a Sorted Array
A sequential search can be more efficient if the data is sorted
Coins sorted by their mint dates.
12
Binary Search of Sorted Array
Algorithm for a binary search
Algorithm binarySearch(a, first, last, desiredItem)mid = (first + last)/2 // approximate midpointif (first > last)
return falseelse if (desiredItem equals a[mid])
return trueelse if (desiredItem < a[mid])
return binarySearch(a, first, mid-1, desiredItem)else if (desiredItem > a[mid])
return binarySearch(a, mid+1, last, desiredItem)
13
Binary Search of Sorted Array
A recursive binary search of a sorted array that (a) finds its target;
14
Binary Search of Sorted Array
A recursive binary search of a sorted array that (b) does not find its target.
15
Java Class Library: The Method binarySearch
The class Arrays in java.util defines versions of a static method with following specification:
/** Task: Searches an entire array for a given item.* @param array the array to be searched* @param desiredItem the item to be found in the array* @return index of the array element that equals desiredItem;* otherwise returns -belongsAt-1, where belongsAt is* the index of the array element that should contain* desiredItem */public static int binarySearch(type[] array, type desiredItem);
16
Efficiency of a Binary Search
Eliminates about half of the array from consideration after examining the middle element once. Counting the maximum number of comparisons under the worst-caseComparison is made each time the array is divided in half. First, begin with n items, first division left us with n/2 items, then second division left us with n/4 items, then third division left with n/8 items, until we get one element. n/2^k = 1 what is k for the total number of division?
If n is a power of 2, k = log2n. If not, find a k such that:
2^(k-1) <n< 2^k; (k-1)<log2n<k
17
Efficiency of a Binary Search
Best case O(1)• Locate desired item first
Worst case O(log n)• Must look at all the items
Average case O(log n)
18
Iterative Sequential Search of an Unsorted Chain
A chain of linked nodes that contain the entries in a list.
Consecutive entries in the list beginning from the first.
Moving from node to node is not as simple as moving from one array location to another.
Use next to point to the next node.
19
Iterative Sequential Search of an Unsorted Chain
Implementation of iterative sequential search
public boolean contains(Object anEntry){ boolean found = false;
Node currentNode = firstNode;while (!found && (currentNode != null)){ if (anEntry.equals(currentNode.getData()))
found = true;else
currentNode = currentNode.getNextNode();} // end whilereturn found;
} // end contains
20
Recursive Sequential Search of an Unsorted Chain
Recursive search method/** Task: Recursively searches a chain of nodes for desiredItem,* beginning with the node that current references. */private boolean search(Node current, Object desiredItem){ boolean found;
if (current = = null)found = false;
else if (desiredItem.equals(current.getData()))found = true;
elsefound = search(current.getNextNode(), desiredItem);
return found;} // end search
21
Efficiency of a Sequential Search of a Chain
Best case O(1)• Locate desired item first
Worst case O(n)• Must look at all the items
Average case O(n)• Must look at half the items• O(n/2) is just O(n)
22
Searching a Sorted Chain
Method to search a sorted chainpublic boolean contains(Object anEntry){ boolean found = false;
Comparable entry = (Comparable)anEntry;Node currentNode = firstNode;while ( (currentNode != null) &&
(entry.compareTo(currentNode.getData()) > 0) ){ currentNode = currentNode.getNextNode();} // end whileif ( (currentNode != null) &&
entry.equals(currentNode.getData()) ){ found = true;} // end ifreturn found;
} // end contains
Note: Binary search of a chain of linked nodes is impractical. It is less efficient than sequential
search
Note: Binary search of a chain of linked nodes is impractical. It is less efficient than sequential
search
23
Choosing a Search Method
Use a sequential search to search a chain of linked nodes.
For array of objects, need to know which is applicable. • Sequential search, must have a method
equals• Binary search,
• must have a method compareTo • and array must be sorted.
24
Choosing a Search Method
Iterative search saves time, memory over recursive search. Usually, we use iterative version for the sequential search. For binary search, coding the binary search recursively is easier than coding it iteratively. Since binary search is fast, recursive will not require much additional space for recursive calls.
BestCase
AverageCase
WorstCase
Sequential search(unsorted data)
O(1) O(n) O(n)
Sequential search(sorted data)
O(1) O(n) O(n)
Binary Search(sorted array)
O(1) O(log n) O(log n)