Searching an element in an array can be performed in two ways.
a. Linear search: We scan all the elements of the array from start to end and one by one compare the array elements to item that we need to search. This method however may take time but can search the item irrespective of whether the array element are sorted or not.
b. Binary search: When we know that the array elements are sorted, we can use binary search by comparing item with middle element of the array. If middle_element == item
, we end the search, else If item > middle_element
, we continue the search in second half of the array else in the first half of the array and continue this process until the element is found or array half becomes zero. This way with each compare we reduce the size of array by half and discard searching in the other half.
For simplicity, let us try to search item in an array using linear search method.
// C program to search item in an array #include <stdio.h> #include <stdlib.h> #define ARR_SIZE 10 /* lin_arr - linear arrat where we have to search the element * n - number of elements currently present in the array, must be less than or equal to ARR_SIZE * item - data element that we need to search in lin_arr */ void search(int lin_arr[], int n, int item) { //exit if n is greater than ARR_SIZE if (n >= ARR_SIZE) exit(1); //exit, if n is negative if (n < 0) exit(1); //initialize loop variable i to 0 and found to 0 (set found = 1 if element is found) int i=0, found=0; //loop untill last element or element is found while (i < n) { if(lin_arr[i] == item) { found=1; break; } i++; } // end of while if (found == 1) printf("Found the element %d at %d position in array\n\n",item,i); else printf("Element %d not present in the array\n\n",item); } // end of search() int main() { int arr[ARR_SIZE] = {1,2,3,4,5,6,0,0,0,0}; int i = 0; printf("Array elements are: \n"); for(i = 0; i < ARR_SIZE; i++) printf("%d,", arr[i]); printf("\n"); // search element 3 in the array printf("Searching element 3 in the array\n"); search(arr,6,3); // search element 8 in the array printf("Searching the element 8 in the array\n"); search(arr,6,8); return 0; } // end of main ####################### Output: Array elements are: 1,2,3,4,5,6,0,0,0,0, Searching element 3 in the array Found the element 3 at 2 position in array Searching the element 8 in the array Element 8 not present in the array
Share this page on WhatsApp