Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 135,947 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,729 people online right now. Registration is fast and FREE... Join Now!




binarysearch

 
Reply to this topicStart new topic

binarysearch, convert my binarysearch into function as pointer

chess0905
9 May, 2008 - 11:28 PM
Post #1

New D.I.C Head
*

Joined: 26 Oct, 2007
Posts: 5


My Contributions
cpp
#include <stdio.h>
#include <conio.h>
#define INDEX 10


void swap (int *, int *);

int main () {
int a[INDEX];
int x,y;
int beg,end,mid,target;

clrscr();

printf ("Enter 10 numbers:\n\n");
for (x=0;x<INDEX;x++)
scanf ("%d",& a[x]);

for (y=0;y<INDEX;y++)
for (x=0;x<INDEX;x++)

if ( a[x] > a[x+1])
{
swap (&a[x],&a[x+1]); //swap pointer and function//
}
printf ("\nIn Ascending 0rder\n");
for (x=0;x<INDEX;x++)
printf ("%4d",a[x]);
printf ("\n");

beg=0;
end=9;


printf ("\nEnter the number to be searched:");
scanf ("%d", &target);

binarysearch (&beg,&end,&mid)//pointer function
while (beg<end&&a[mid]!=target)
{
mid=(beg+end)/2;
if ( target<=a[mid])

end= mid-1;
else
beg=mid+1;
mid=(beg+end)/2;
}
if (a[mid]==target)
{
printf ("\nThe number is found at position");
printf (" a[%d]",mid);
}
else{
printf ("\n The number is not found.");
}
getch ();
return 0;

}



void swap (int *p,int *q)
{
int temp;
temp=*q;
*q=*p;
*p=temp;

}


***the binary search should be converted into function using pointer. i couldn't make it run, please help. thanks
User is offlineProfile CardPM
+Quote Post

Mike007
RE: Binarysearch
10 May, 2008 - 09:17 AM
Post #2

D.I.C Head
Group Icon

Joined: 30 Aug, 2007
Posts: 205


Dream Kudos: 75
My Contributions
Well you have a few problems there. First your logic seems to be very wrong. I don't know why you would want to get the beginning, middle and end positions as arguments to your function. What binarysearch functions usually look like is this:
cpp

int binarySearch(int* array, int find)
{
// binary search algorithm
// .
// .
}


So you only get the array and what you are searching for. Another reason your code wasn't working because you didn't properly define your function as a function.

Good luck.

This post has been edited by Mike007: 10 May, 2008 - 09:17 AM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/1/08 08:51AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month