-
December 6th, 2008, 11:36 AM
#1
Word Array in List
Hi, I have a minor problem my code does not seem to go to the loops and do a selection search or any search this is my code:
Code:
#include <stdio.h>
#include <conio.h>
int linearsearch(char a[], char v, int l, int r)
{ int i;
for (i = l; i <= r; i++)
if (v == a[i]) return i;
return -1;
};
//--------------------
int binarysearch(char a[], char v, int l, int r)
{
while (r >= l)
{ int m = (l+r)/2;
if (v == a[m]) return m;
if (v < a[m]) r = m-1; else l = m+1;
}
return -1;
};
//-------------------------
void selection(char a[], int l, int r)
{ int i, j, t;
for (i = l; i < r; i++)
{ int min = i;
for (j = i+1; j <= r; j++)
if (a[j] < a[min]) min = j;
t = a[i];
a[i]= a[min];
a[min] = t;
}
};
//------------------------------------
void bubble(char a[], int l, int r)
{ int i, j, t;
for (i = l; i < r; i++)
for (j = r; j > i; j--) {
t = a[j-1];
a[j-1] = a[j];
a[j] = t;
}
};
main(void)
{
int i;
char findme[20];
int found;
char *list[] = {"Cat", "Dog", "House"};
printf("Enter a character to find: ");
scanf("%s", &findme);
selection(*list,0,0);
found = binarysearch(*list,findme[20],0,0);
if (found == -1) printf("\n\n%s is not in the list.",findme);
else printf("\n\n%s is in position %d of the list.",findme,found);
getch();
};
-
December 6th, 2008, 12:11 PM
#2
Re: Word Array in List
Originally Posted by botter911
Hi, I have a minor problem my code does not seem to go to the loops and do a selection search or any search this is my code:
Arrays are indexed starting from 0 up to n-1, where n is the number of items in the array. Arrays do not start at 1, and your code will erroneously overwrite memory (if the loops were working).
Second, why are you passing 0 here:
Code:
selection(*list,0,0);
The value of "r" in the function will be 0. So you're looping from 1 to 0, meaning the loop will never execute. You do the same mistake with binarysearch and linearsearch.
You need to loop through the proper indices of an array (0 to r-1), and pass the correct numbers to these functions (and also, learn to use the debugger, as these problems are found easily by using your compiler's interactive debugger).
Regards,
Paul McKenzie
-
December 6th, 2008, 08:27 PM
#3
Re: Word Array in List
Thanks for your help.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|