Showing posts with label Searching Algorithm.. Show all posts
Showing posts with label Searching Algorithm.. Show all posts

Algorithm to search element in the Linked list

Search_LL(List, element, Start)

Here, List is a Linked list containing n elements, in which we have to search element. Start is a pointer which is containing the address of starting Node. SUCCESS=1 is a constant which will be returned on successful search and FAILURE=0 is a constant which will be returned on unsuccessful search. Ptr is a intermediate pointer which is used to traverse the list.

Step 1: [check, if list is empty]
            If Start = null then 
                   return FAILURE;
Step 2: Ptr = Start
Step 3: While Ptr < > null repeat step 4
Step 4: i) If Ptr -> Data = Element then 
                    return SUCCESS;
           ii) Ptr = Ptr->Next
Step 5: return FAILURE;
Step 6: End

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.