If the element to be searched is lower than the mid element, we will set the high pointer to the "mid-1" element and run the algorithm again. If the element to be searched is greater than the mid, we will set the low pointer to the "mid+1" element and run the algorithm again. We will compare the mid element with the element to be searched and if it matches, we will return the mid element. Now, we will find the middle element of the array using the algorithm and set the mid pointer to it. Now, we will set two pointers pointing the low to the lowest position in the array and high to the highest position in the array. Return BinarySearch(array, k, low, mid - 1)Ĭonsider the following array on which the search is performed. Return BinarySearch(array, k, mid + 1, high) else // k is on the right side Return mid else if k > array // k is on the right side Algorithm for Binary Search (Iterative Method)īinarySearch(array, k, low, high) if low > high The steps of the process are general for both the methods, the difference is only found in the function calling. There are two methods by which we can run the binary search algorithm i.e, iterative method or recursive method. If the list is not sorted, then the algorithm first sorts the elements using the sorting algorithm and then runs the binary search function to find the desired output. The most important thing to note about binary search is that it works only on sorted lists of elements. Binary search algorithms are fast and effective in comparison to linear search algorithms.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |