Faster way to search list?

时间:2016-10-20 20:03:37

标签: c++ algorithm list binary-search linear-search

I'm trying to make my program run more efficiently, and I believe fixing this linear search would do a great deal of help in terms of speed, but am curious as to how I'd go about changing this to something like binary search, as I believe the list isn't necessarily ordered. Is there some way of ordering the list based on it's first argument key?

What I'm working with currently:

int* key_sequences::data(int key){
    for(it=myList.begin(); it!=myList.end(); ++it){
        if(it->first==key){
            return &(it->second[0]);
        }
    }
    return nullptr;
};

1 个答案:

答案 0 :(得分:0)

Searching in a simply linked list is O(n), where n is the size of the list.

However, in some implementations, people use three list pointers, one at the start, one at the middle and one at the end, so that when searching comes up - they can speedup the process, so you can search online for this.

BUT, if I were you and was so interesting in speeding up the search, I would try another data structure (hash? like std::unordered_map) or sort the list.