Practice exercise: Problem Solving and Algorithms(7b)
1. Array:
Declare item an int array with 10 components indexed from 0 through 9.
Input and assign a value to each item[] component. Echo the values stored.
2. Linear and Sequential Search:
a. Extend step 1 to search item[] for a particular value. Assume this is an
unsorted array and search until the value is found or until all item[]
components have been checked. After the search ends, output a message to
show whether(or not) the value was found.
Set index to 0
Set found to false
Repeat while index is less than length and found is false
if item[index] equals searchItem
set found to true
else increment index
if found
output search item "found"
else output "not found"
b. Develop code to search a sorted array. That is, the values are stored in
(ascending) order. In this case stop the search when the value is found or
when the search has passed the place where it should be stored. Output a
message stating whether(or not) the value was found in the array.
Set index to 0
Set found to false
Repeat while index is less than length and (search item) NOT found:
if item[index] equals the search item
set found to true,
else if item[index] greater than search item
set index to length
else
increment index;
if found
output search item "found"
else output "not found"
3. Binary Search("method of halving"):
Given a sorted array named data, apply a divide and conquer strategy that
starts the search from the middle component in data[], and if the data
value sought is not there decide whether to search the first half of data[]
or the second half. Look in the chosen half and repeat the strategy.
A binary search algorithm:
Set first to 0
Set last to length - 1
Set found to false
while (first less than or equal to last AND NOT found)
Set middle to (first + last) / 2
if (itemValue equals data[middle])
Set found to true
else
if (itemValue less than data[middle])
Set last to middle - 1
else
Set first to middle + 1