Searching Arbitrary Arrays

[comp1110-87]

Binary Search is very efficient, but depends on the array being sorted. This may not be true of any array you might encounter. So, as a first attempt, you might want to use the sortedness checker from Example [comp1110-1K] to see if the array is sorted, and then depending on that either use binary search or the linear search procedure we saw in Example [comp1110-16].

boolean search(int[] haystack, int needle) { if(isSorted(haystack)) { return binarySearch(haystack, needle); } else { return linearSearch(haystack, needle); } }

The problem with the above approach is that when we are checking whether the array is sorted, we have to go through every element of the array. At that point, we might just check whether those elements are equal to needle right away.

The general idea is more reasonable if there are several things that we want to search for. In that case, we only have to go through the array once, and if it happens to be sorted, we can then use binarySearch many times, efficiently finding each element.

But better yet, in that case, we might just want to sort the array to guarantee that we can do those later searches efficiently.

bars magnifying-glass caret-down plus minus arrow-right xmark