In: Computer Science
You are an analytics developer, and you need to write the searching algorithm to find the element. Your program should perform the following: Implement the Binary Search function. Write a random number generator that creates 1,000 elements, and store them in the array. Write a random number generator that generates a single element called searched value. Pass the searched value and array into the Binary Search function. If the searched value is available in the array, then the output is “Element found,” or else the output is “Not found.” This question must be done in Code Blocks for C++
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define SIZE 1000
void bubbleSort(int array[],int n) {
int i, j, temp;
for (i = 0; i < n - 1; ++i)
{
for (j = 0; j < n - 1 - i; ++j) {
if (array[j] > array[j + 1]) {
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
}
// performs binary search on the array and returns
the number of
// comparisions
int binarySearch(int arr[], int l, int r, int x, int
comp) {
if (r >= l) {
int mid = l + (r
- l) / 2;
if (arr[mid] ==
x) {
return mid;
}
if (arr[mid]
< x)
return binarySearch(arr, mid+ 1, r, x,
comp);
return
binarySearch(arr, l, mid - 1, x, comp);
}
return -1;
}
int main() {
int *a= new int[SIZE];
for (int i = 0; i < SIZE; ++i)
{
a[i] =
rand()%1000;
}
bubbleSort(a,SIZE);
// generating element to search in
the array
int ele=rand()%1000;
// calling binary search
if(binarySearch(a, 0, SIZE, ele,
0)==-1)
cout<<"Not found";
else
cout<<"Element found";
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me
Not found ... Program finished with exit code 0 Press ENTER to exit console.