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

后端 未结 8 1101
孤城傲影
孤城傲影 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:00
    int add(Container c, int r, int l, Unit t)
    {
        if(c[r]>t)
            return r;
        if(c[l]<t)
            return l+1;
        if(c[r]==c[l])
        {
             if(c[r]==t)
                return -1;
             return -1;
        }
        int m=(r+l)/2;
        if(c[m]==t)
              return -1;
        if(c[m]>t)
              return add(c,m,l,t);
        if(c[m]<t)
              return add(c,r,m,t);
    }
    

    It will probably give you the index you need to add...I hope it can help.It assumes you do not need to add when its already in.

    0 讨论(0)
  • 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 <algorithm>
    #include <iostream>
    #include <iterator>
    #include <vector>
    
    int main()
    {
        std::list<int> 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

    0 讨论(0)
提交回复
热议问题