binary search

hi,
im trying to write something that'll give the the symetrical difference between two sets of nubers (if A = {1, 3, 5, 7} and B = {2, 4, 6, 7}, C = {1, 3, 5}- all the numbers that are in A and arent in B).
this is my code- can anyone tell me where i went wrong?

#include <iostream>
using namespace std;
bool BinarySearch(int set2[], int size, int num)
{
int begin = 0, end = size - 1, mid;
while (begin < end)
{
mid = (begin + end) / 2;
if (set2[mid] == num)
return true;
if (num < set2[mid])
end = mid - 1;
else begin = mid + 1;
}
return false;
}

int main()
{
int set1[6], set2[6], difference[6], j = 0;
bool tf;
cout << "enter first 6 numbers:" << endl;
for (int i = 0; i < 6; i++)
cin >> set1[i];
cout << "enter next 6 numbers:" << endl;
for (int i = 0; i < 6; i++)
cin >> set2[i];
for (int i = 0; i < 6; i++)
{
tf = BinarySearch(set2, 6, set1[i]);
if (tf == false)
{
j++;
difference[j - 1] = set1[i];
}
}
cout << "set difference is:" << endl;
if (j == 0)
cout << "empty" << endl;
else
for (int i = 0; i < j; i++)
cout << difference[i] << " ";
cout << endl;
}
Last edited on
Please describe you problem.

my problem is that I don't know what my problem is- the output is wrong, but I don't know if the problem is in the BinarySearch function or in the main section. i know this is a very in-the-air question but I really don't know how to fix this
So your problem is that the output is incorrect?

What did you input into the program?

What output does the program produce?

What output do you expect to get with the given input?


while (begin < end)
should be
while (begin <= end)

Please use code tags and give a full description of the problem, as @jlb requested.
If the problem is that there is one element too many the problem is before the while(), using the less than should be preferred.

1
2
int begin = 0, end = size - 1 /* This is the problem, why the subtraction?*/, mid;  
while (begin < end)



Last edited on
Topic archived. No new replies allowed.