Exercise: Search an
unordered array.
An array table might,
or might not, contain a certain value
element.
const int
MAX_SIZETABLE = 1000;
int table[MAX_SIZETABLE];
int sizeTable;
bool found;
You may assume that sizeTable has been assigned the number of values stored in the array, and the
first sizeTable elements of the array, namely table[0] .. table[sizetable-1] have been assigned values.
Write some code that scans
the array and assigns true to the variable
found if it finds the element, or
assigns false if it does not find the element.
Do NOT code
|
found = false; for ( int i = 0; i
< sizeTable; i++ ) { if ( table[i] == element ) found = true; } |
since it is too inefficient. Stop scanning as soon as you find the element (if it exists.)
Answer:
|
found = false; for ( int i = 0; i
< sizeTable; i++ ) { if ( table[i] == element ) { found = true; break; } } |
alternate code
|
found = false; for ( int i = 0; i
< sizeTable && ! found; i++ ) { if ( table[i] == element ) found = true; } |
alternate code NOT
RECOMMENDED
|
found = false; for ( int i = 0; i
< sizeTable; i++ ) { if ( table[i] == element ) { found = true; i = sizeTable; } } |
alternate code - depends on
short-circuit evaluation of Boolean expressions
|
found = false; int i; for ( i = 0; i
< sizeTable && table[i] != element; i++ ) /* do nothing */; found = ( i < sizeTable ); |
table[i] != element is not evaluated when i >= sizeTable
Evaluating table[i] when i >= sizeTable is an out of array bounds error.