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

后端 未结 8 1099
孤城傲影
孤城傲影 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 05:52

    From what I can see, you're using a C array to store your entries, which means a big penalty in performance with huge number of entries whenever you try to insert an new entry because you may need to move a lot of entries in the array.

    If you plan to keep a C array and not using some stl ordered containers (mostly thinking about std::map though), you may try to split your C array into two arrays. One will be a first array containing your key and an index to an element of the second array. You still need to sort the first array but its element is only two words (one for key, one for index) instead of a big block including key and some values) and should be faster. When inserting an item, you allocate at the end of the second array and take the index to insert it as a pair with key inside the first array. If you plan to remove an element dynamically, you can be a little smarter but your question appears not to cover it.

    But even so, it might be still too slow, so you should indeed consider std::map or some algorithms like binary tree using AVL, Red Black tree, Splay tree, etc. where you do not need to move element physically.

提交回复
热议问题