0

im trying to get the best possible way to find a member im currently using linear search (i think) witch i did something like this

void srchbook(book* books){
    char tempstring[maxsize];
    int i;
    printf("enter the id of the book you want to find:\n");
    gets(tempstring);
    for(i=0;i<bookcount;i++){
        if (!strcmp(tempstring,books[i].id)){
            printf("the book you wanted is: %s\n",books[i].title);
            printf("author: %s\n",books[i].author);
            printf("year of release: %s\n",books[i].year);
            printf("pages: %s\n",books[i].pages);
            printf("Genre: %s\n",books[i].subject);
            break;
        }
    }
    if(i >= bookcount){
        printf("no result :(\n");
    }
    printf("issue another command\n");
    pick(books);
}

is there anyway i can make it more efficient? i was thinking of binary search but im not really sure it would be more efficient. also if i did the search recursively would it made any impact?

unwind
  • 391,730
  • 64
  • 469
  • 606
Omer Guttman
  • 141
  • 8
  • 3
    binary search on sorted list would be far more efficient, yes, because complexity is greatly reduced (doesn't show on a few items) – Jean-François Fabre Apr 11 '17 at 09:36
  • 1
    I agree with @Jean-FrançoisFabre, for more than a few items, a binary tree would always be faster. If you have loads of time, then you could even try a balanced AVL tree, which is even quicker – mikeyq6 Apr 11 '17 at 09:37
  • 5
    [DO NOT use `gets()`, it is dangerous](http://stackoverflow.com/q/1694036/2173917). use [`fgets()`](https://linux.die.net/man/3/fgets) instead. – Sourav Ghosh Apr 11 '17 at 09:37
  • @Jean-FrançoisFabre,but i wouldnt i need to sort the array first wouldent that make run time longer? – Omer Guttman Apr 11 '17 at 09:38
  • 2
    @OmerGuttman That, of course, "depends". There are no one-size fits all answers in optimization, since it quickly becomes usage-dependent. If you do four million searches for every insertion, then it probably makes sense to optimize for search, and the other way around. We can't know. – unwind Apr 11 '17 at 09:41
  • 1
    Generally, binary search is faster, but not always. The "number of comparisons" is a very bad metric to measure execution speed with, that's some 1980s mind set. If a linear search would result in better data cache use than binary search, it may very well be faster. Branch prediction vs memory access time. Which is an advanced and highly system-specific subject. – Lundin Apr 11 '17 at 09:42

0 Answers0