Wednesday, 15 July 2015

Trying to recursively binary search strings in c -



Trying to recursively binary search strings in c -

i need utilize binary search recursively find target string. function should homecoming -1 if not found , positive integer if found returns -1. help!

int start = 0; int search; search = binary_search(strings, target, start, size-1); if(search == -1) { printf("not in dataset!"); } if(search != -1) { printf("%s in dataset", target); } int binary_search(char **strings, char *target, int start_idx, int end_idx) { if(end_idx < start_idx) { homecoming -1; } int middle = ((start_idx + end_idx)/2); int i; = strcmp(target, strings[middle]); if(i == 0) { homecoming middle; } if(i < 0) { homecoming binary_search(strings, target, start_idx, middle-1); } else { homecoming binary_search(strings, target, middle+1, end_idx); } }

input data: aden caden david erik john mark matt mycah phil susan

although binary search notoriously hard right, don't see errors in algorithm shown. can still fail (-1) due various causes can not determined based on info provided.

1) source strings list not sorted correctly -- strcmp() uses ascii comparison, not dictionary comparison, i.e., source string must ascii sorted bsearch valid.

2) source strings not well-formed nul terminated c strings.

3) target string not have exact match in source string list. i.e., searching "bill" not match "bill" or "billiard"

just note, recursive bsearch slower , uses more memory non-recursive solution

c string recursion binary-search

No comments:

Post a Comment