Arrays - Arrays and Searching Sorted Arrays A very common...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Arrays and Searching A very common programming process. Sequential Search : the simplest method. Begin search at one end of the array and scan down it until the desired value is found or the other end is reached. Algorithm: int find(int big_array[], int size, int value) { int found=0, loc = 0; while(!found && loc < size){ if (big_array[loc] == value) found = 1; else loc = loc + 1; if (found) return loc; else return –1; } 2 Sorted Arrays What happens if the array is sorted? we can terminate search as soon as a value which is greater than or equal to the target value is found. Algorithm: while (!found && loc < size){ if (big_array[loc] >= value) found = 1; else loc = loc + 1; } if (found && big_array[loc] != value) found = 0;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
3 Binary Search Sequential search is easy to implement and efficient for short arrays, but it is a disaster for long arrays. (e.g. trying to find “Smith” in a telephone directory with sequential search) To find an item in a long list, there are far more efficient methods. & Binary search
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This document was uploaded on 06/12/2011.

Page1 / 5

Arrays - Arrays and Searching Sorted Arrays A very common...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online