- Preparation
- Selection Sort
- Compare Searching Algorithms
You can store your work for this part in the Searching directory.
You have been given the code for performing a Binary Search in the zip folder provided for this exercise. As a side reference, the code for performing a Sequential Search was also given.
Step 1-Modify the Binary Search
To get a better understanding of how the Binary Search is working, add some statements to the routine. i.e. Make these changes in BinSearch.cpp
- Create a local variable in the BinarySearch function called "loopCtr" and initialize it to 1.
- After the
difference = intArray[mid] - target; statement, add some cout statements to print some headings and the values ofTarget: Mid: Difference: LoopCtr:
- After your new cout statements, add these statements:
printArray(intArray, mid);
loopCtr++;
Step 2-Compare the Runs
Run the code and search for the first, middle, and last items. Based on your observations, construct the following table in a file and save it to show your lab instructor:
Sequential | Binary | |
---|---|---|
Is the data sorted? (yes or no) | ||
How many comparisons are made to find the first item (index 0)? | ||
How many comparisons are made to find the middle item (index 49)? | ||
How many comparisons are made to find the last item (index 99)? |
Step 3-Challenge Questions
Save these questions and your answers to the same file as above.
Suppose your array contained 1,000,000 elements:
- For a Sequential Search, how many comparisons would the program need to find the last value in the array?
- For a Binary Search, how many comparisons would the program need to find the last value?
- In this case, which do you think will be faster?