Binsearch problem

Task is to make programm searching in array of structs by num. It's compiled, but gets error when i type what student to find
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<stdio.h>
#include<stdlib.h>
using namespace std;

struct students 
{
	int num;
	char name[32];
	int mark;
};

int binsearch(struct students arr[], int value, int left, int right) {
      while (left <= right) {
            int middle = (left + right) / 2;
            if (arr[middle].num == value)
                  return middle;
            else if (arr[middle].num > value)
                  right = middle - 1;
            else
                  left = middle + 1;
      }
      binsearch(arr, value, left, right);
}
 
int comp(const void *i, const void *j) 
{
	if (((struct students*)i)->num - ((struct students *)j)->num > 0) return 1;
	if (((struct students*)i)->num - ((struct students *)j)->num < 0) return -1;
	if (((struct students*)i)->num - ((struct students *)j)->num == 0) return 0;
}

int main()
{
	int n,q;
    scanf("%d",&n);
    struct students* mass = new struct students[n];
    for (int i = 0; i < n; ++i) 
	{
		scanf("%d %s %d", &(mass[i].num), (mass[i].name), &(mass[i].mark));
    }
    qsort(mass, n, sizeof(struct students), comp);
    for (int i = 0; i < n; ++i) 
	{
		printf("%d %s %d\n", (mass[i].num), (mass[i].name), (mass[i].mark));
	}
	scanf("%d", &q);
	binsearch(mass,q,mass[0].num,mass[n-1].num);
    return 0;
}
The problem is in your call to the function binsearch(mass,q,mass[0].num,mass[n-1].num); num could have any number (and that is what you are looking for), but in your function they translate to left and right.
left and right are indexes of your array, so they can go from 0 to n-1 and left<=right.

Also, you need to handle the case where the value is not in the array.
Edit: why the recursive call, if you handle everything with a while loop?
1
2
3
4
5
6
7
8
9
10
11
12
int binsearch(struct students arr[], int value, int left, int right) {
      while (left <= right) {
            int middle = (left + right) / 2;
            if (arr[middle].num == value)
                  return middle;
            else if (arr[middle].num > value)
                  right = middle - 1;
            else
                  left = middle + 1;
      }
      binsearch(arr, value, left, right); //how the program could reach this line? (in a "I mean to do that" way)
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int bsearch(int Array[],int down,int up,int X) {
	int med;
	do {
		med = (down+up)/2;
		if (X > Array[med])
			down = med + 1;
		else
			up = med - 1;
	} while (Array[med] != X && down <= up);
	
	if (Array[stred] == X)
		return stred;
	else 
		return -1;
}
Topic archived. No new replies allowed.