#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2009
    Posts
    9
    Rep Power
    0

    Performing Binary Search from text file


    Hey there..

    I'm looking forward to create a program that prompts the user to input a name. If the input name exists in the array of records, the complete name, age, weight and height will be printed out on screen.

    All the data mentioned above, stored in .txt file..

    My question is, how am I going to do binary search if all the data in text file.. i can do it if it's entered by user.. but, from text file?
    i really dont have any idea.. :confused:
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,392
    Rep Power
    1871
    First, you create an index for your text file.
    Code:
    long positions[MAX_RECORDS];
    int nRecords = 0;
    positions[nRecords++] = ftell(fp);
    while ( fgets( buff, sizeof(buff), fin ) ) {
        positions[nRecords++] = ftell(fp);
    }
    To do a binary search, you first start with
    Code:
    fseek( positions[nRecords/2] );
    fgets( buff, sizeof(buff), fin );
    parse buff, decide whether what you want is before or after, and pick an appropriate next record to fseek to.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2009
    Posts
    9
    Rep Power
    0
    Originally Posted by salem
    First, you create an index for your text file.
    Code:
    long positions[MAX_RECORDS];
    int nRecords = 0;
    positions[nRecords++] = ftell(fp);
    while ( fgets( buff, sizeof(buff), fin ) ) {
        positions[nRecords++] = ftell(fp);
    }
    To do a binary search, you first start with
    Code:
    fseek( positions[nRecords/2] );
    fgets( buff, sizeof(buff), fin );
    parse buff, decide whether what you want is before or after, and pick an appropriate next record to fseek to.
    Thanks.. i'll do it first.. :tbulb:
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2009
    Posts
    9
    Rep Power
    0
    guys..
    I've done it.. it works perfectly with help from my friend..
    but..
    i don't understand, why should i include BUFFER?

    for example, he ask me to include the line below and define it..
    fgets(temp,BUFFER-1,fptr)
    why i need buffer? :confused:

IMN logo majestic logo threadwatch logo seochat tools logo