Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
- bool linearSearch(int arr[], int num,int &linear_count) {
- for (int i = 0; i < 50; i++) {
- linear_count++;
- if (num == arr[i]) {
- return true;
- break;
- }
- }
- return false;
- }
- void bubbleSort(int arr[]) {
- int key(0);
- for (int j = 0; j < 49; j++) {
- for (int i = 0; i < 49; i++) {
- if (arr[i] > arr[i + 1]) {
- key = arr[i + 1];
- arr[i + 1] = arr[i];
- arr[i] = key;
- }
- }
- }
- }
- bool binarySearch(int first, int last, int arr[], int num, int& binary_count) {
- int mid(0);
- binary_count++;
- if (first <= last) {
- mid = (first + last) / 2;
- if (arr[mid] == num)
- return true;
- else if (num > arr[mid])
- binarySearch(mid + 1, last, arr, num, binary_count);
- else
- binarySearch(first, mid - 1, arr, num, binary_count);
- }
- else
- return false;
- }
- int main() {
- int arr[50]; int num = 0; int linear_count=0; int binary_count = 0;
- srand(time(0));
- for (int i = 0; i < 50; i++) {
- arr[i] = rand();
- }
- cout << "Enter the number you want to search for \n";
- cin >> num;
- cout << "Using the linear search:\n";
- cout << "-------------------------\n";
- if (linearSearch(arr, num, linear_count))
- cout << "The number is existed after " << linear_count << " of comparisons\n";
- else
- cout << "The number is not there after " << linear_count << " of comparisons\n";
- bubbleSort(arr);
- cout << "\n";
- cout << "Using the binary search:\n";
- cout << "-------------------------\n";
- if (binarySearch(0, 49, arr, num, binary_count))
- cout << "The number is existed after " << binary_count << " of comparisons\n";
- else
- cout << "The number is not there after " << binary_count << " of comparisons\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement