1 Take a look through elements of an array one by one, until searched value is found. If required value doesn't exists in our array, then we will pass all array, all elements. In average, complexity of such an algorithm is O(n) n- count of elements.
2. Sort array using any in place sort algorithms, QuickSort for instance, and then apply Binary Search algorithm.
Algorithm
Algorithm is very simple. It can be done either recursively or iteratively:
- get the middle element;
- if the middle element equals to the searched value, the algorithm stops;
- otherwise, two cases are possible:
- searched value is less, than the middle element. In this case, go to the step 1 for the part of the array, before middle element.
- searched value is greater, than the middle element. In this case, go to the step 1 for the part of the array, after middle element.
I decided to implement it recursive way with a few enhancements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class BinarySearch { public int Search private int InnerSearch |
No comments:
Post a Comment