# Thread: help with binary search

1. ## help with binary search

ok i sorted an array of structures and now i need help placing them in boxes
so that the number of boxes required is optimal

i have an idea of what i could do

- find the biggest item possible, and switch it with the first element of the array
-decrease my box' size by the item chosen and search another item
-With the new item, you switch it with the 2nd element of the array
-You repeat it until all the items have been switched

here is my code so far that sorts my array...i just dont know how to use the binary search
i attached the input file im using

Code:
```#include <stdio.h>
#include <stdlib.h>

typedef struct {
int size;
char name[21];
int boxnumber;
int used;
}item;

void swap(item *a, item *b){
item tmp;
tmp = *a;
*a = *b;
*b = tmp;
}

void bubbleSort(item a[], int size){
int i, j;

for (i=0; i<size-1; i++){
for (j=size-1; j>i; j--)
if (a[j].size > a[j-1].size)
swap(&a[j], &a[j-1]);
}
}

int bfind(item a[],int val,  int size){
int left = 0;
int right = size;
int middle;

do {
middle = (left + right) / 2;

if(a[middle].size < val)
left = middle + 1;
else if(a[middle].size > val)
right = middle - 1;
else
return middle;
} while(left <= right);

return middle-1;
}

int main(void) {
int s,n;
int i;
int newboxsize;
item *array;

FILE *iFile;
iFile = fopen ("inputzou.txt","r");

fscanf (iFile, "%d, %d", &s, &n);

printf (" \n");

array = calloc (n, sizeof(item));

for (i=0;i<n;i++){
array[i].boxnumber=0;
array[i].used=0;

fscanf(iFile, "%s %d", array[i].name, &array[i].size);
}

bubbleSort(array, n);

free(array);

fclose(iFile);

return 0;
}```

2. Ummm...what exactly is it you're trying to do ?
Is it 0-1 knapsack or are you actually trying to search an array with binary search ? It's not quite clear what the question is...

3. So what is the actual problem with the code

ssharish2005