I am programming c on linux and I have a big integer array, how to filter it, say, find values that fit some condition, e.g. value > 1789 && value < 2031. what’s the efficient way to do this, do I need to sort this array first?
I’ve read the answers and thank you all, but I need to do such filtering operation many times on this big array, not only for once. so is iterating it one by one every time the best way?
Sort the array first. Then on each query do 2 binary searches. I’m assuming queries will be like –
First binary search would find the index
iof the element such thatArray[i-1] <= a < Array[i]and second binary search would find the indexjsuch thatArray[j] < b <= Array[j+1]. Then your desired range would be[i, j].This algorithm’s complexity is
O(NlogN)in preprocessing andO(N)per query if you want to iterate over all the elements andO(logN)per query if you just want to count the number of filtered element.Let me know if you need help implementing binary search in C. There is library function named
binary_search()in C andlower_bound()andupper_bound()in C++ STL.