





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A C++ program for implementing linear and binary search algorithms to find a given number in an array. The user can input the array size and values, and then use the menu to choose between linear and binary search. The program displays the location of the number if found, or a message indicating that it was not found.
Typology: Assignments
1 / 9
This page cannot be seen from the preview
Don't miss anything!






#include
int linearSearch(int a[], int size, int search_num) { for (int i = 0; i < size; i++) { if (a[i] == search_num) { return i; } else return -1; } }
int binarySearch(int a[], int first, int last, int search_num) { int middle; if (last >= first) { middle = (first + last) / 2; if (a[middle] == search_num) { return middle + 1; } else if (a[middle] < search_num) { return binarySearch(a, middle + 1, last, search_num); } else { return binarySearch(a, first, middle - 1, search_num); } } return -1;
case 1: { system("cls"); std::cout << " ----------------------------- " << std::endl; std::cout << " sTORE ARRAY VALUES " << std::endl; std::cout << " ----------------------------- " << std::endl; for (int i = 0; i < size; i++) { std::cout << "Please enter value for location " << i << std::endl; std::cin >> num[i]; } break; } case 2: { system("cls"); std::cout << " ----------------------------- " << std::endl; std::cout << " LINEAR SEARCH " << std::endl; std::cout << " ----------------------------- " << std::endl; int search_num, loc = -1; std::cout << "Enter the number that you want to search: linear search " << std::endl; std::cin >> search_num;
loc = linearSearch(num, size, search_num); if (loc != -1) { std::cout << search_num << " found in the array at the location: " << loc << std::endl; } else { std::cout << " not found through linear search" << std::endl;; } break; } case 3: { system("cls"); std::cout << " ----------------------------- " << std::endl; std::cout << " BINARY SEARCH " << std::endl; std::cout << " ----------------------------- " << std::endl; int search_num, loc = -1; std::cout << "Enter the number that you want to search: through binary " << std::endl; std::cin >> search_num; loc = binarySearch(num, 0, size, search_num);