Arrays
More skills
Search
- Search for 10
- Search starts at the first element in the list, that is, at list[0]
- This time, the search item, which is 10, is compared with every item in the list; eventually, no more data is left in the list to compare with the search item; this is an unsuccessful search
Linear search
public static int seqSearch(int[] list, int listLength, int searchItem) { int loc; boolean found = false; loc = 0; while (loc < listLength && !found) if (list[loc] == searchItem) found = true; else loc++; if (found) return loc; else return -1; }
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.
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.
The binarySearch method returns the index of 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.
/** 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; } return -1 - low; }