Binary search in array is not working properly [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
// function for binary search in array
#include <iostream>
using namespace std;
int binSrch(int arr[], int n, int key)
{
int s = 0, e = n; // s for starting and e for ending
int mid = (s + e) / 2;
while (s <= e)
{
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
e = mid - 1;
else
s = mid + 1;
}
return -1;
}
int main()
{
int n, key;
cout << "enter no. of elements" << endl;
cin >> n;
int arr[n];
cout << "enter array " << endl;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "enter key" << endl;
cin >> key;
cout << binSrch(arr, n, key);
return 0;
}
This code for binary searching in array does not work.
For some array the program gets stuck. I don't know what did wrong.
I entered input in sorted format.
PS C:\Users\anmol\Desktop\c++projectwork> g++ .\binSearchArrFun.cpp
PS C:\Users\anmol\Desktop\c++projectwork> ./a
enter no. of elements
6
enter array
2
3
4
5
6
7
enter key
8
it just stuck here rather than giving -1

Assuming that you are passing n as the size of the array, you should give e = n-1 since arrays are 0-indexed based, that is where you are probably getting the wrong answer.
And you also should calculate mid after each iteration, so it should be inside the while loop.
Also, you should do mid = s +(e-s)/2 to avoid overflow.

I modified your code. Run it and it should become clear what's going on.
#include <iostream>
using namespace std;
int binSrch(int arr[], int n, int key)
{
int s = 0, e = n; // s for starting and e for ending
int mid = (s + e) / 2;
while (s <= e)
{
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
{
cout << "e = mid - 1;\n";
e = mid - 1;
}
else
{
cout << "e = mid - 1;\n";
s = mid + 1;
}
}
return -1;
}
int main()
{
int n = 4, key = 3;
int arr[100] = { 1,3,4,10 };
cout << binSrch(arr, n, key);
return 0;
}
You can use this modified main for testing. It ouputs test cases that don't work.
int main()
{
int n = 4;
int arr[] = {1,3,4,10,11};
// check for each element of arr if it is found
// at the right position
int index = 0;
for (auto testval : arr)
{
if (! binSrch(arr, n, testval) == index)
cout << "not OK for case" << testval << "\n";
index++;
}
// check if 0 and 100 are not found
if (binSrch(arr, n, 0) != -1)
cout << "not OK for case" << 0 << "\n";
if (binSrch(arr, n, 100) != -1)
cout << "not OK for case" << 100 << "\n";
return 0;
}

Related

Extra "0" in output when factorizing a number

Write a function int fact(int n) which displays the factors of the integer n, and returns the number of factors. Call this function in main() with user input
#include<iostream>
using namespace std;
int fact(int n);
int main() {
int n,factor;
cout << "Enter an integer : ";
cin >> n;
factor = fact(n);
cout << factor;
return 0;
}
int fact(int n)
{
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
cout << i << endl;
}
return 0;
}
If I enter 7, I get 1,7,0 . How do i remove this 0 and how do i find the number of factors?
You should count in your int fact() function. Set a variable to 0 and increment each time you currently display i. Then at the end of the function instead of returning 0 return the count variable.
int fact(int n)
{
int count=0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
count++;
}
}
return count;
}
The key part is "and returns the number of factors". You don't do that. Keep a count of the factors:
int fact(int n)
{
int count = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
{
// found a factor, add to the count
count++;
cout << i << endl;
}
}
// return the count instead
return count;
}
Then, your main function can use that count:
factor = fact(n); // fact(n) will already print the factors
// now just print the number
cout << "Number of factors: " << factor << '\n';
#include <iostream>
#include <vector>
std::vector<int> fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
std::vector<int> factors = fact(n);
for (auto i : factors) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "Number of factors: " << factors.size() << '\n';
return 0;
}
std::vector<int> fact(int n) {
std::vector<int> vec{1};
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
vec.push_back(i);
}
}
vec.push_back(n);
return vec;
}
If you're going to return anything from fact(), it should be the factors. To do so, I am using a std::vector. It is an array that can grow on demand. The numbers 1 and n are always factors, so I don't bother doing the math for them. The vector is initialized already holding the value 1, and I only calculate numbers up to and including half of n (Anything greater than n/2 won't divide evenly, so my loop is finished about half as fast by recognizing the actual range). I then just add n to the vector, which I return.
My main prints the vector, and the vector knows its own size, which is the number of factors.
Alternatively, you can just keep a count in your fact() function.
#include <iostream>
#include <vector>
// Prints factors of n and returns the number of factors
int fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
int numFactors = fact(n);
std::cout << "Number of factors: " << numFactors << '\n';
return 0;
}
int fact(int n) {
int factorCount = 2; // Already counting 1 and n
std::cout << "1 ";
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
std::cout << i << ' ';
++factorCount;
}
}
std::cout << n << '\n';
return factorCount;
}
The main problem with your code is that your function always returns zero. You need to keep a count of factors and return it.
Besides that your code performance badly as the loop goes on much longer than needed. You can use the square root of n as the limit in the for loop. Like:
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int limit = sqrt(n);
for (int i = 1; i <= limit; ++i)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
}
if (limit * limit == n)
{
--res;
}
return res;
}
For n = 36 the output is:
1 - 36
2 - 18
3 - 12
4 - 9
6 - 6
and the returned value is 9
Below is another approach. It doesn't use square root. Instead it keeps the number of loops low by using the square of i as loop limit.
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int i = 1;
int i_square = i * i;
while (i_square < n)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
++i;
i_square = i * i;
}
if (i_square == n)
{
++res;
cout << i << " - " << n/i << endl;
}
return res;
}
Fact() always returns 0 so this line print 0
cout << factor;
for the number of factors you can change the return value of fact() :
int fact(int n)
{
int nb = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
nb++;
}
}
return nb;
}

how is the output going to get displayed?

i was writing a c++ code for performing binary search in an array,but am unable to wield the desired output. when execute the code, i ma getting a never ending output, what may be the reason behind this?
#include <iostream>
using namespace std;
void Binary(int arr[], int n, int key)
{
int s = 0;
int e = n - 1;
while (s <= e) {
int mid = (s + e) / 2;
if (arr[mid] == key) {
cout << "Element Found At Index No. " << mid;
} else if (arr[mid] > key) {
e = mid - 1;
} else {
s = mid + 1;
}
}
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cout << "Enter element to be searched!";
cin >> key;
Binary(arr, n, key);
return 0;
}
After you find your element, you generate output but never exit the loop or change either of the values that the loop condition checks.
Simply break out of the loop (or return from the function) after showing your output:
if (arr[mid] == key) {
cout << "Element Found At Index No. " << mid;
break;
}
Answer provided by #1201ProgramAlarm is the right fix. Adding few minor changes:
Instead of using namespace std; it would be better to explicitly provide the scope resolution for std::cin and std::cout
Providing some more print statements while entering the array elements.
#include <iostream>
void Binary(int arr[], int n, int key)
{
int s = 0;
int e = n - 1;
while (s <= e) {
int mid = (s + e) / 2;
if (arr[mid] == key) {
std::cout << "Element Found At Index No. " << mid;
break;
} else if (arr[mid] > key) {
e = mid - 1;
} else {
s = mid + 1;
}
}
}
int main()
{
int n;
std::cout << "Enter Number of elements in the array: ";
std::cin >> n;
int arr[n];
std::cout << "Enter " << n << " sorted array elements: ";
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
int key;
std::cout << "Enter element to be searched!";
std::cin >> key;
Binary(arr, n, key);
return 0;
}

C++ program wont compile with expected expression and function not allowed here

#include <iostream>
using namespace std;
const int lab8 = 10;
int labArray[lab8];
void promptUser(int [], int);
void sortArray(int [], int);
void showArray(const int[], int);
int searchArray(const int [], int, int value);
int x = 0;
int results = 0;
int main()
{
promptUser(labArray, lab8);
sortArray(labArray, lab8);
showArray(labArray, lab8);
cout << "Choose an integer you want to search from the array: " << endl;
cin >> x;
results = searchArray(labArray, lab8, x);
if (results == -1) {
cout << "That number does not exist in the array. \n";
else
{
cout << "The integer you searched for was for at element " << results;
cout << " in the array. \n";
}
}
void promptUser(int numbers[], int size)
{
int index;
for (index = 0; index <= size - 1;index++ )
{
cout << "Please enter ten numbers to fill the array " << endl
<< (index + 1) << ": ";
cin >> numbers[index];
}
}
void sortArray(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size -1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
void showArray(const int array[], int size)
{
for (int count = 0; count < size; count++)
{
cout << "The array you entered when sorted was: ";
cout << array[count] << " ";
cout << endl;
}
}
int searchArray(const int array[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = - 1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
I am new to c++ and just working on an assignment for my class. I thought the program I wrote would have worked but for the life of me I can not figure out why it will not compile. I am sure I am missing something or not understanding how it should work completely. The errors I keep receiving are expected expression on line 26 by the 'else' statement and when I put the 'if' and 'else' statements in I started receiving function not allowed here errors. Any help would be greatly appreciated.
In the if statement, you open the bracket { but you never close it. Not sure if this is the problem but it should raise some issues.
if (results == -1) {
cout << "That number does not exist in the array. \n";
**}**
else
{
cout << "The integer you searched for was for at element " << results;
cout << " in the array. \n";
}
This is how it should look. Try it

Taking in multiple inputs at once and then giving out output at once [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So my question is how to efficiently write a program where in we are able to take multiple inputs (the amount of inputs given is determined by the user) and then give the outputs at once. Lets consider a program which gives gives the sum of its digits. Eg - 12345 = 15.
//Single input single output
#include <iostream>
using namespace std;
int main()
{
int T, N;
cout << "Enter the value of T (No. of test cases)" << endl;
cin >> T;
cout << "Enter the value of N : " << endl;
while (T > 0)
{
cin >> N;
int ans = 0,temp1,temp2;
while(N!=0)
{
temp1= N %10;
N = (N - temp1)/10;
ans = ans + temp1;
}
cout << ans << endl;
T--;
}
return 0;
}
// Taking in all inputs then giving out all outputs ( Not working properly)
#include <iostream>
using namespace std;
int SumCal(int Number, int TestCase, int t);
int main()
{
int N, T;
cout << " Enter the value of T ( Total number of test cases) " << endl;
cin >> T;
int *Ans(new int[T]);
if (T >= 1 && T <= 1000)
{
cout << "Enter the value of N" << endl;
for (int i = 1; i <= T; i++)
{
cin >> N;
if (N >= 1 && N <= 100000)
Ans[i] = SumCal(N, i, T);
}
}
for (int z = 1; z <= T; z++)
{
cout << Ans[z] << endl;
}
delete[] Ans;
return 0;
}
int SumCal(int Number, int TestCase, int t)
{
int temp1, temp2 = 0;
int *AnsTemp(new int[t]);
temp1 = Number % 10;
temp2 = Number / 10;
if (temp2 < 10 && temp2 > 0)
AnsTemp[TestCase] = (temp1 + temp2);
while (temp2 > 10)
{
AnsTemp[TestCase] = (AnsTemp[TestCase] + temp1);
temp2 = temp2 / 10;
temp1 = temp1 % 10;
}
return AnsTemp[TestCase];
delete[] AnsTemp;
}
// This will work properly for multiple inputs multiple outputs
#include <iostream>
using namespace std;
int SumCal(int Number, int TestCase);
int main()
{
int N, T;
cout << " Enter the value of T ( Total number of test cases) " << endl;
cin >> T;
int Ans[1000] = {};
if (T >= 1 && T <= 1000)
{
cout << "Enter the value of N" << endl;
for (int i = 1; i <= T; i++)
{
cin >> N;
if (N >= 1 && N <= 100000)
Ans[i] = SumCal(N, i);
}
}
for (int z = 1; z <= T; z++)
{
cout << Ans[z] << endl;
}
return 0;
}
int SumCal(int Number, int TestCase)
{
int temp1, temp2 = 0;
int ans;
temp1 = Number % 10;
temp2 = Number / 10;
if (temp2 < 10 && temp2 > 0)
ans = (temp1 + temp2);
while (temp2 > 10)
{
ans = (ans + temp1);
temp2 = temp2 / 10;
temp1 = temp2 % 10;
}
return ans;
}
These are the codes I could think of. The first one is a simple one, which takes in an input and then gives out a output. In the second one I tried to use dynamic memory allocation but the program gives error. ( I know I haven't made proper use of * and & in it but I already tried using it in various manners and failed). The third program is successful but as we are setting up a large constraint value to the array, (i.e int Ans[1000]) it makes the program a bit inefficient.
So my question is how would one dynamically allocate memory during runtime successfully to take in multiple inputs and then give multiple outputs at once.
It's very hard to work with your code. I just took the 1st example, minimized the code and did what you should have done:
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int T;
cout << "Enter the value of T (No. of test cases)" << endl;
cin >> T;
int *buf = new int[T](); // buffer to hold the answers
for(int i = 0; i < T; ++i)
{
int N;
cout << "Enter the value of N : " << endl;
cin >> N;
while(N)
{
buf[i] += N % 10; // calculate on the buffer element
N /= 10;
}
}
for(int i = 0; i < T; ++i)
cout << buf[i] << endl; // print the buffer
delete [] buf; // delete buffer
return 0;
}
There's not much to do for managing the dynamically allocated array here, but take a look at std::vector and its uses.

Having problems with binary search c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Im having a problem with a binary search function. It only seems to work when the randomly generated search key is already in the middle position of the array. Ive tried a lot of things but cant seem to figure out why it's doing this.
#include<iostream>
#include<ctime>
using namespace std;
void printarray(int[], int);
void fillarray(int[], int);
void descendingSort(int[], int);
int binarySearch(int[], int, int);
int main()
{
srand((unsigned int)time(0));
bool quit = false;
while (quit == false)
{
int key = rand() % 100 + 1;
const int size = 16;
int mainarray[size] = {};
fillarray(mainarray, size);
printarray(mainarray, size);
descendingSort(mainarray, size);
cout << endl;
cout << "Ordered array after selection sort:" << endl;
printarray(mainarray, size);
cout << endl;
int result = binarySearch(mainarray, size, key);
cout << "Searching for key value " << key << endl;
if (result >= 0)
{
cout << "Key value " << key << " found at position " << result << endl;
}
else
{
cout << "Key value " << key << " not found!" << endl;
}
cout << "Continue (y/n)? :";
char x;
cin >> x;
cout << endl;
if (x == 'y')
quit = false;
if (x == 'n')
quit = true;
}
return 0;
}
void printarray(int array[], int size)
{
for (int i = 0; i < size; i++)
{
cout << array[i] << " ";
}
}
void fillarray(int random[], int size)
{
for (int j = 0; j <= size - 1; j++)
{
random[j] = rand() % 100 + 1;
}
}
void descendingSort(int array[], int size)
{
int max, next;
for (int i = 0; i < size - 1; i++)
{
max = i;
for (int j = i + 1; j < size; j++)
{
if (array[max] < array[j])
max = j;
}
if (max!= i)
{
next = array[i];
array[i] = array[max];
array[max] = next;
}
}
}
int binarySearch(int array[], int size, int key)
{
int low = 0, high = size - 1;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
if (key == array[mid])
{
return mid;
}
else if (key < array[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return -1;
}
Since you are sorting in descending order, your case is backwards.
See code below where I replaces > with <
if (key == array[mid])
{
return mid;
}
else if (key > array[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
By adding some code above the if it allowed me to visualize what was going wrong.
cout << "Searching in: ";
for (int i = low; i < high + 1; i++)
{
cout << array[i] << " ";
}
cout << endl;