Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

C. Do you consider this message warm and inviting?

Answered: 1 week ago

Question

3. Identify cultural universals in nonverbal communication.

Answered: 1 week ago

Question

2. Discuss the types of messages that are communicated nonverbally.

Answered: 1 week ago