Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Binary search, recursive.
- #include <iostream>
- using namespace std;
- // Find a number in a list.
- int find_number(int number_list[], int number_to_find,
- int range_start, int range_end)
- {
- int index_of_found_number = 0;
- int range_middle; // This is the current middle of the range.
- // If we have searched all the sections,
- if (range_start > range_end) {
- index_of_found_number = -1; // The number is not on the list.
- }
- // If there is more to search,
- else {
- // Find the middle of the range.
- range_middle = (range_start + range_end) / 2;
- // If the middle number is equal to the number we're looking for,
- if (number_list[range_middle] == number_to_find) {
- // It was found in the middle.
- index_of_found_number = range_middle;
- }
- // If the middle number is greater than the number we're looking for,
- else if (number_list[range_middle] > number_to_find) {
- // Search the range before the middle number.
- index_of_found_number = find_number(number_list, number_to_find,
- range_start, range_middle - 1);
- }
- // If the middle number is less than the number we're looking for,
- else {
- // Search the range after the middle number.
- index_of_found_number = find_number(number_list, number_to_find,
- range_middle + 1, range_end);
- }
- }
- return index_of_found_number;
- }
- int main()
- {
- // List of numbers to search.
- int numbers[] = {2, 4, 6, 7, 9, 10, 14, 15, 17, 19, 26, 29};
- // Calculate the number of elements in the array.
- int num_elements = sizeof(numbers) / sizeof(int);
- int input = 0; // The number to look for.
- int index = 0; // Index of found number.
- cout << "What number would you like to find? ";
- cin >> input; // Get the number we are searching for.
- // Search for the number.
- index = find_number(numbers, input, 0, num_elements - 1);
- // If if the number was not found.
- if (index == -1) cout << "The number " << input
- << " is not on the list.\n";
- // Otherwise, if the number was found, display the
- // index where it was found
- else cout << "The number " << input << " is located at index "
- << index << '\n';
- // End the program.
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement