Fastest way to search for an element in unsorted array

后端 未结 10 1769
北恋
北恋 2020-12-14 08:13

I just bumped on to this question today and was trying for a solution that is better than O(N) but could not come up with one.

Searched through SO but couldn\'t find

相关标签:
10条回答
  • 2020-12-14 09:06

    If you're searching for one element once, just iterate through it. No possible way to get it faster.

    If you're searching multiple times, it would be worth it to index it (or sort it, if you will) and make the following searches fast (log(n)).

    0 讨论(0)
  • 2020-12-14 09:06

    This could be solved by using some tricks. In an unsorted array simly if we traverse through it, the complexity in worst case (when element is present at last index) would be O(N), where N is the size of array. So, here is the trick. First check the last index so that if the element is present at last index (the worst case) our code will be executed in O(1). and after that while the code to traverse and find the element. So, now the worst case complexity would be O(N-1).

    int findElement(int N, int arr[], int element){
      if(arr[N]==element){
        return i;
      }
      for(int i=0; i<N-1; i++){
        if(arr[i]==element)
          return i;
      }
      return -1;
    }
    
    0 讨论(0)
  • 2020-12-14 09:13

    Make it parallel. Divide the array in chunks and search in parallel. The complexity will be O(n) but running time will be much less. Actually it will be proportional to no. of processors you have.

    You can use Parallel Patterns Library in C++

    0 讨论(0)
  • 2020-12-14 09:15

    It is possible to make your program run faster than O(n).

    You start off by sorting the array using the merge sort algorithm, then you use binary search to find the element. Both algoro have a running time of O(log_2(n)). Adding these two complexities together, you get 2*log_2(n), which is O(log_2(n)) with the witness C = 2.

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