Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With respect to an array containing a lot of duplicate elements, is there any operations to improve the performance of normal binary search?

Tags:

algorithm

With respect to an array containing a lot of duplicate elements, is there any operations to improve the performance of normal binary search?

like image 442
bit-question Avatar asked Dec 22 '22 01:12

bit-question


2 Answers

You can create two arrays. One for values, and the other for repetitions. Then, you can search the values array using binary search.

like image 89
Khaled Alshaya Avatar answered Jan 25 '23 23:01

Khaled Alshaya


AraK's answer is 'the only' answer. In general you can't improve worst-case performance on any array with duplicates. Let's say your duplicates tend to concentrate on the end of the array. Now you're looking for an element towards the beginning: your search will have to run as usual.

If you know that duplicates tend to appear on one side more often, you can skew the splitting to improve average performance. If they appear towards the end, e.g., you can do the first split at 1/3 instead of 1/2.

like image 33
Mau Avatar answered Jan 25 '23 23:01

Mau