Question: Having issues using binary search on a pointer array. 1. Write 1000 random ints to file 2. Binary Search to find if number exists in

Having issues using binary search on a pointer array.

1. Write 1000 random ints to file

2. Binary Search to find if number exists in element from file.

int main()

{

ArrayActions action;

int count;

int userInput;

int num = 1000;

int array[num];

ofstream myFile ("/Users/chan/Desktop/LANEY_CIS27/Assignemtn2_CIS27/Assignemtn2_CIS27/File.txt");

//Set srand with time to generate unique random numbers

srand((unsigned)time(0));

//Format random num up to 999

for(count = 0; count < num; count++)

{

array[count] = rand() % 1000;

}

//Condition to check if file is open

if (myFile.is_open())

{

for (int i = 0 ; i < num; i++)

{

//Write all random values to myFile

action.bubblesort(array, num);

myFile << array[i] << " ";

}

cout << "------Ouput is written to myFile-------- ";

//Close File

myFile.close();

}

else

cout<<"File doesn't exist. ";

cout << "Enter input from menu: ";

cin >> userInput;

//int n = sizeof(array) / sizeof(array[0]);

int result = action.binarySearch(array, 0, num-1, userInput);

if (result == -1)

cout << "Element is not present in array ";

else

cout << "Element is present at index " << result << endl;

int binarySearch(int *arr, int l, int r, int x)

{

while (l <= r) {

int m = l + (r - l) / 2;

// Check if x is present at mid

if (arr[m] == x)

return m;

// If x greater, ignore left half

if (arr[m] < x)

l = m + 1;

// If x is smaller, ignore right half

else

r = m - 1;

}

// if we reach here, then element was

// not present

return -1;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!