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

痴心易碎 提交于 2019-12-12 22:16:51

问题


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 the 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;
        }

回答1:


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;



回答2:


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



来源:https://stackoverflow.com/questions/6966462/method-to-get-to-the-middle-of-the-file-for-binary-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!