LINEAR

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

AIM: linear and binary search.

Software used: VS Code


Algorithm:
1. Include Necessary Header:
 The code includes the necessary header file <stdio.h> for input/output
operations.
2. Linear Search Function:
 Defines a function linearSearch that takes an array arr[], its size n, and a
key to search for.
 Iterates through the array using a for loop and checks if the current
element is equal to the key.
 Returns the index if the key is found; otherwise, returns -1.
3. Binary Search Function:
 Defines a function binarySearch that takes an array arr[], the low and
high indices, and a key to search for.
 Uses a while loop to perform binary search on the sorted array.
 Calculates the middle index ( mid) and compares the element at mid with
the key.
 Adjusts the search range accordingly and continues until the key is
found or the search range is exhausted.
 Returns the index if the key is found; otherwise, returns -1.
4. Main Function:
 Initializes a sorted array arr[].
 Computes the size of the array n.
 Prompts the user to enter an element ( key) to search for.
5. Linear Search:
 Calls the linearSearch function to perform linear search on the array.
 Prints whether the element is found or not in the array.
6. Binary Search:
 Calls the binarySearch function to perform binary search on the sorted
array.
 Prints whether the element is found or not in the array.
7. Return Success Code:
 Returns 0 to indicate successful execution.

Flowchart:
Source Code:
#include <stdio.h>

// Function for linear search


int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Return the index if the key is found
}
}
return -1; // Return -1 if the key is not found
}

// Function for binary search


int binarySearch(int arr[], int low, int high, int key) {
while (low <= high) {
int mid = low + (high - low) / 2;

if (arr[mid] == key) {
return mid; // Return the index if the key is found
} else if (arr[mid] < key) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}

return -1; // Return -1 if the key is not found


}

int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 45, 50};
int n = sizeof(arr) / sizeof(arr[0]);

int key;
printf("Enter the element to search: ");
scanf("%d", &key);

// Perform linear search


int linearIndex = linearSearch(arr, n, key);
if (linearIndex != -1) {
printf("Linear Search: Element %d found at index %d.\n", key,
linearIndex);
} else {
printf("Linear Search: Element %d not found in the array.\n", key);
}

// Perform binary search (requires a sorted array)


int binaryIndex = binarySearch(arr, 0, n - 1, key);
if (binaryIndex != -1) {
printf("Binary Search: Element %d found at index %d.\n", key,
binaryIndex);
} else {
printf("Binary Search: Element %d not found in the array.\n", key);
}

return 0;
}

OUTPUT :

You might also like