C++ - Fastest way to add an item to a sorted array

后端 未结 8 1225
孤城傲影
孤城傲影 2021-01-23 05:18

I\'ve got a database with approximately 200 000 items, which is sorted by username. Now when I add an item to end of array and call my quick sort function to sort that array it

8条回答
  •  忘掉有多难
    2021-01-23 06:01

    Reinventing the wheel is fine if you want to learn how to code binary search, otherwise reusing is better.

    std::lower_bound performs a binary search on a sorted range [first, last), returning an iterator to the searched element x if already present; otherwise the iterator would be pointing to the first element greater than x. Since standard containers' exposing an insert would insert before the iterator, this iterator can be used as-is. Here's a simple example.

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::list data = { 1, 5, 7, 8, 12, 34, 52 };
    
        auto loc = std::lower_bound(data.begin(), data.end(), 10);
        // you may insert 10 here using loc
        std::cout << *loc << '\n';
    
        loc = std::lower_bound(data.begin(), data.end(), 12);
        // you may skip inserting 12 since it is in the list (OR)
        // insert it if you need to; it'd go before the current 12
        std::cout << *loc << '\n';
    }
    

    12

    12

提交回复
热议问题