Click here to load reader
Upload
ferdinand-townsend
View
215
Download
1
Embed Size (px)
Citation preview
CSCI 130
Array Searching
Methods of searching arrays
• Linear– sequential - one at the time– set does not have to be ordered
• Binary– continuously cutting the set in half– set must be ordered
Linear Search
• Checking each value in the array sequentially
• Ex: – assume x is a 10 element integer array and we are
searching for the number 16 for (y = 0; y < 10; y++) { if (x[y] == 16) { printf(‘16 found!!!’); } }
Linear Search
• Instead of searching all 10 elements everytime, we should end the loop if we find the search value
for (y = 0; y < 10; y++) { if (x[y] == 16) { printf(‘16 found!!!’); break; } }
Linear Search
• For a search set of 10 elements, the average number of ‘tries’ to find an element is 5– number of tries = 1/2 the number of elements
• For a set of n elements, n/2 ‘tries’ are needed
Linear Search - Advantages
• Easier to write
• Easier to understand
• Set does not have to be ordered
Binary Search
• Set must be ordered– Alphabetically or numerically
• Binary searches are more efficient for large sets of data– smaller sets are just as efficient with linear
searches
Binary search algorithm
• Find the midpoint of the set• Determine if the array element at the midpoint
subscript is greater than the search value– If so, cut the list in half and search only from the previous
start to the cut point– If not, cut the list in half and search only from the cut point
to the previous finish
• Continue doing this until the difference between the endpoints is 1
• Interrogate the array at both endpoints
Binary search algorithm while ((finish - start) > 1) { if (numArray[curValue] > 100) { finish = curValue; curValue = (finish - start) / 2; } else { start = curValue; curValue = start + (finish - start) /2; }
}
if ((numArray[start]==16)||(numArray[finish]==16)) {
printf(‘16 found!!!’); }
Binary Search
• For a search set of 2 elements, 0 tries are made before the comparisions
• For a search set of 4 elements, 1 try is made before the comparisons
• For a search set of 8 elements, 2 tries are made before the comparisons
• For a search set of x elements, n tries are made before the comparisons where:
2n < x <= 2(n+1)
Binary Search
• How many ‘tries’ are needed to search for a value in an ordered set of 100000 elements?
• 216 = 65536 < 100000 < 217 = 131072
• Hence 16 tries before the comparisons, or 18 tries after the comparisons
Binary Search - Advantages
• Efficiency for larger sets
• Lookup time is consistent– Lookup time for linear will vary