Showing posts with label Search in Array. Show all posts
Showing posts with label Search in Array. Show all posts

Algorithm: Binary Search in Array

Binary search algorithm is enhancement in searching of element in array, It reduces worst case complexity of of linear search from O(n) to O(log2n). In this algorithm all the elements in the array must be sorted.

BinarySearch(ArrayValues[], n, searchValue, LB, UB)

Here ArrayValues is an array of size n, Which is already sorted. In which we have to search an element searchValue. LB is lower bound and UB is an upper bound of the array. Mid is an intermediate variable which will contains middle element of array.

Algorithm: Linear Search For Array


In Linear Search algorithm whole array is traversed to search the element untill the element found.

Linear_Search(valArr[], n, searchValue)

Here valArr[] is of length n, and SearchValue  is a value which is to be found in the array. Consider lower bound of the array is 1. this algorithm will return index of first occurrence of the searchValue, and returns -1 on failure.

Step1: [Iterate the array]
           For index=1 to n repeat step 2 and 3

Step2:  if valArr[index]=searchValue then goto step 2(i) else goto step 3
                  i) return index

Step3: if index=n then goto step 3(i) else goto step 3(ii)
            i) return -1;
            ii) index=index-1;

Step4: End.