Binary search using pointers(in C)

Status
Not open for further replies.
I have to create a binary search using pointer for a school assignment. I haven't had much luck getting it to work (please keeping mocking and laughter to a minimum)

int Search(int num[], int n, int target)
{
int pos = 0, *first=num, *mid, *last;
last=(num+n);


SortData(num, n);



printf("%d", num[1]);

while (first <=last)
{
mid=(first+last)/2;
if (target >mid)
first=mid+1;
else if (target <mid)
last=mid-1;
else
{ first = last+1;

return (*mid-2);
}}

return -1;
}

It gives me the standard "Why the F are you screwing around with Memory that ain't yours" error.
 

MrMills

Ars Praefectus
3,727
Moderator
Richard Berg:
Also, whenever you have something like pointer+=1 it should probably be pointer+=sizeof(data_type).

No, C does pointer arithmetic very well. If you have an int pointer and increment it, the actual value will increase by four.

Locke:
still seems to march off the end of the array

Hmm ... it shouldn't if you're returning *mPtr. You are returning *mPtr, not (*mPtr - 2), right?

By the way, this is one place where a good debugger is essential. Learn how to debug, and your life as a programmer will become much easier.
 

kurt-o

Ars Praefectus
4,370
Moderator
This is what my buddy tells me

... main( ... )
{
declare an array of ints...

allocate it, fill it, whatever...

sort them... SortData( ... );
}

before the sort was done inside the search...

which is useless because the point of the search
is to find the element that matches the searched value.

if you sort inside the search, then the index is useless
outside... and you don't want to sort everytime, or bsearching
is a waste...

Search() takes an array of ints, size of the array, and a search value...

it returns the index of the targe in the array, or -1 if it's not found.

if there are duplicate values in the list, the index returned won't
always point to the first element that matches.

oh btw i didn't compile it or test it but it should be fine...
you should really read over it though.. the original had alot of problems
so it might take you a bit to understand why it's written this way...

and you might check out doing this operation with recursion as well.
code:<HR>
Code:
int Search( int *nlst, int ncnt, int target )
{
  int pos = 0;
  int first;
  int mid;
  int last;<P>  first = 0;
  last  = ncnt;<P>//  printf( "%d", nlst[0] );<P>  while ( first <= last ) {
    mid = (first+last)/2;
    if ( target > nlst[mid] ) {
      first = mid + 1;
      continue;
    }<P>    if ( target < nlst[mid] ) {
      last = mid - 1;
      continue;
    }<P>    return mid;
  }<P>  return -1;
}
 

petrov

Ars Tribunus Militum
2,714
Originally posted by Locke:
I have to create a binary search using pointer for a school assignment. I haven't had much luck getting it to work (please keeping mocking and laughter to a minimum)

actually, Jon Bentley's Programming Pearls spends a bit of time on this very topic noting that Knuth pointed out that the first binary search was published in the 1940s, it wasn't until the 1960s that the first bug-free binary search was published. It's hard to get a bug-free binary search, so don't beat yourself up too much,

--sam
 

Citrus538

Ars Legatus Legionis
12,722
code:<HR>
Code:
int Search(int num[], int n, int target)
{
  int pos = 0, *mid;
  int *first = num;
  int *last = (num + n);<P>  SortData(num, n);<P>  printf("%d", num[0]);<P>  while (first <= last)
  { 
    mid = (first + last) / 2;<P>    if (target > *mid)
      first = mid + 1;
    else
      if (target < *mid)
        last = mid - 1;
      else
      {
        first = last + 1;
        return (*mid - 2);
      }
  }<P>  return -1;
}

First of all, "mid" is a pointer so you need to dereference it when comparing it to "target".

Second, did you check what (first + last) / 2 does?
Is it equal to first + (sizeof(int) * last)) / 2
or actually (first + last) / 2
 

Frogfoot

Smack-Fu Master, in training
88
I'm wishing I had a text book and a chalkboard to map this on.
The logic is giving me a headach.

I'm not sure you can use num like that before it is declared.
would wait to do it where the logic is more clear
then num+n returns what exactly? num = int *first what is num?

does using num return the size of num[]?if so, what is "n"?

wish I had linux running. I could 'man' the commands and find out what they do exactly.

sucks for me to be a noob.
 

technophile

Ars Legatus Legionis
23,768
The logic is fairly simple: Look at the array element in the center of the (sorted) array. If the value you're looking for is less than the value of that element, then you do the same thing (pick the middle element and compare) using only the left half of the array. If the value you're looking for is greater than the element you pick, you repeat using only the right half of the array. In each iteration, you throw away half of the array, so your search narrows quite quickly. It's a very efficient search if your array is pre-sorted.

Example:

Array: 1 4 5 6 8 10 12
Search for 4
1st iter: Choose middle element (6)
4 < 6 so throw away 6,8,10,12
Array: 1 4 5
2nd iter: Choose middle element (4)
4 == 4 so we have found our element and the search returns.
If we had been looking for 1, we'd have done one more iteration, having thrown away 4 and 5.

Originally posted by Frogfoot:
I'm not sure you can use num like that before it is declared.
would wait to do it where the logic is more clear
:confused: num is declared in the function declaration, and is passed into the function. He can use num anywhere in the function safely assuming he passes in a valid pointer.

does using num return the size of num[]?if so, what is "n"?
num is the address of the first element of the array (since arrays are actually pointers to the first array element, and the subsequent array elements are immediately contiguous in memory). Standard C usage. n is the number of elements in the array since, in C, standard arrays do not know their own length.
 
Status
Not open for further replies.