开发者

Method to get to the middle of the file for Binary Search

开发者 https://www.devze.com 2023-03-26 03:22 出处:网络
I am doing an assignment where I\'ve got given a program which reads in a data file and spits out the data into an array of bytes, where th开发者_运维知识库e first 4 bytes of the array tell you how ma

I am doing an assignment where I've got given a program which reads in a data file and spits out the data into an array of bytes, where th开发者_运维知识库e first 4 bytes of the array tell you how many people's names it has (the data file contains). Following the rest of the array which holds strings of the names of the people. This array is pointed to by a const void * foo;

For example, the first 4 bytes say there are 5 names stored into the array, and the next 4 bytes tell you the address of the person's name. The person's name is stored in the array

int num = ((int*)foo)[0];
const int ppl1 = ((int*)foo)[1];
string name = ((char*)foo)+ppl1;

so num would tell you theres 5 names in the array and ppl1 would tell you the position of the array where you can find the first name and name collects the name of the person located at that slot of the array.

Pretty much, I am given a name to search for in the array, and I wanted to use binary search to doit. I don't know of a way to find the middle of the file though, can you guys give me some pointers?

cheers =]

EDIT: so I created this, but it seg faults and only works for one case (when searching for the first entry). No idea why...

    int first = 0;
    int num = ((int*)foo)[0];
    int last = num;


    while (first <= last) {
        int middle = first+last/2;
        int offset = ((int*)foo)[middle];
        string name = ((char*)foo)+offset;
        if (person < name) {
            last = middle-1;
        } else if (person > name) {
            first = middle+1;
        } else {
            break;
        }


You know the number of elements and the data structure allows you to do a random access to any element:

const int middleOffset = ((int*)foo)[num/2];
string middleName = ((char*)foo)+middleOffset;


The functions seekg and tellg of C++ file streams will allow you to navigate though the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消