0% found this document useful (0 votes)
65 views

Data Structure in Linear Search and Binary Search

The document describes two search algorithms: linear search and binary search. Linear search sequentially checks each element of an array to see if it matches the search key. Binary search divides the search space in half at each step by comparing the search key to the middle element of the array. It returns the index of an element if found or -1 if not found. The example code provided implements and demonstrates both search algorithms on sample arrays.

Uploaded by

isce5b
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Data Structure in Linear Search and Binary Search

The document describes two search algorithms: linear search and binary search. Linear search sequentially checks each element of an array to see if it matches the search key. Binary search divides the search space in half at each step by comparing the search key to the middle element of the array. It returns the index of an element if found or -1 if not found. The example code provided implements and demonstrates both search algorithms on sample arrays.

Uploaded by

isce5b
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 3

Linear Search

#include <stdio.h> #define SIZE 100 int linearSearch (const int array[], int key, int size ); int main() { int a[ SIZE ]; int x; int searchKey; int element; for ( x = 0; x < SIZE; x++ ) { a[ x ] = 2 * x; } printf( "Enter integer search key:\n" ); scanf( "%d", &searchKey ); element = linearSearch( a, searchKey, SIZE ); if ( element != -1 ) { printf( "Found value in element %d\n", element ); } else { printf( "Value not found\n" ); } return 0; } int linearSearch( const int array[], int key, int size ) { int n; for ( n = 0; n < size; ++n ) { if ( array[ n ] == key ) { return n; } } return -1; } Enter integer search key: 2 Found value in element 1

BINARY SEARCH
#include <stdio.h> #define SIZE 15 int binarySearch(const int b[], int searchKey, int low, int high ); void main() { int a[SIZE], I, key = 10, result = -1; for ( i = 0; i < SIZE; i++ ) { a[i] = 2*i;} result = binarySearch( a, key, 0, SIZE-1); if ( result != -1 ) { printf( "\n%d found in array element %d\n", key, result); } else { printf( "\n%d not found\n", key );} } int binarySearch( const int b[], int searchKey, int low, int high ) { int middle; while ( low <= high ) { middle = ( low + high )/2; if ( searchKey == b[middle]) { return middle; } else if (searchKey<b[middle]) { high = middle - 1; } else { low = middle + 1; } } return -1; }

10 found in array element 5

You might also like