You are on page 1of 2

Searching Searching for an element in the list is the process of checking, if a sp ecified element is present in the list and

determining the location of the desired element. There are two method of searchi ng. Sequential(or linear) Search: We are given a list or vector of size n. In this method, the elements ar e scanned from the first one till either the required element is found or the list is exhausted. Algorithm of linear search is Algorithm : Linear_search(A, N, X) Here A is a array with N elements i.e., A [1 : N]. X is the element to b e search. If the search. If the search is successful, this algorithm finds the location or position of X i the array other wisse the value 0 is returned. Step 1 [search he array] Repeat for I = 1 to N If A [I] = X then Return (I) and Exit [End of if statement] [End of for loop] Step 2 [Element not found] Return(0) Exit Write a program to implement linear search. #include<stdio.h> main() { int a[40], n,i,se,found=0; printf("\nEnter the number of element in the array : "); scanf("%d",&n); printf("Enter the array elements\n"); for(i=1;i<n;i++) scanf("%d",&a[i]); printf("Enter the element to be searched for : "); scanf("%d",&se); /*search for array elements*/ i=1; while(i<=n && found == 0) { if(a[i]==se) found = 1; i++; } /*write output*/ if (found ==1) printf("Element found at position : %d",i-1); else printf("Element not found"); } RUN:

Enter the number of element in the array : 5 Enter the array elements 7 8 5 6 3 Enter the element to be searched for : 6 Element found at position : 4

BINARY SEARCH Binary search method can be used only for sorted lists. In this method, the valu e of the element in the middle of the list is compared with the value of the element to be searched for. If the middle element is large, the desired element may be in the upper half of the list. If the middle element is smaller, the desi red element may be in the lower half of the list. Algorithm of binary search is Algorithm Here A is d. If the algorithm quired. : Binary_Search(A, N, X) a array with N elements i.e., A[1 : N]. X is the element to be searche search is successful, this finds the locor position of X in the array otherwise the value 0 is re

Step 1 [Initialize variables] FIRST : = 1 LAST : = N MIDDLE : = INT ((FIRST + LAST)/2) Step 2 Repeat step 3 and 4 while FIRST <= LAST and A[MIDDLE] < > X Step 3 If X < A [MIDDLE] then LAST : = MIDDLE - 1 Else FIRST : = MIDDLE +1 [End of If statement] Step 4 MIDDLE = INT ((FIRST + LAST)/2) [End of step 2 Loop] Step 5 [Result] If A[MIDDLE] = X then Return (MIDDLE) Else Reurn(0) [End of If statement] Step 6 Exit

You might also like