I have an array of integers storing some userIDs. I basically want to prevent a user from performing an action twice, so the moment he has done it his userID enters this array.
I wonder whether it is a good idea to sort or not this array. If it is sorted, then you have A={min, ..., max}. Then, if I'm not wrong, checking if an ID is in the array will take log2(|A|) 'steps'. On the other hand, if the array was not sorted then you will need |A|/2 (in average) steps.
So sorting seems better to check if an element exists in the array (log(|A|) vs |A|), but what about 'adding' a new value? Calculating the position of where the new userID should be can be done at the same time you're checking, but then you will have to displace all the elements from that position by 1... or at least that's how I'd do it on C, truth is this is going to be an array in a MongoDB document, so perhaps this is handled in some other most-effective way.
Of course if the array is unsorted then adding a new value will just take one step ("pushing" it to the end).
To me, an adding operation (with previous checking) will take:
- If sorted:
log2(|A|) + |A|/2. Thelog2part to check and find the place and the|A|/2as an average of the displacements needed. - If not sorted:
|A|/2 + 1. The|A|/2to check and the+1to push the new element.
Given that for adding you'll always first check, then the not sorted version appears to have less steps, but truth is I'm not very confident on the +|A|/2 of the sorted version. That's how I would do it in C, but maybe it can work another way...
dictionaries) have become the go-to data structure when you wantO(1)lookup and are built-in to most modern languages, with mature open-source implementations for languages such as C which lack native support. Furthermore, you seem to be talking about something involving a database -- isn't the point of a data base to give you O(1) access to large amounts of data? Amazon doesn't maintain a sorted list of titles but can instantaneously locate any title. Why not use the database to keep track of what you want to keep track of?