The document contains a C program that implements linear search, bubble sort, and binary search algorithms. It demonstrates searching for a key in an unsorted array using linear search and then sorting the array before performing a binary search. The output confirms that the key was found at the same index in both search methods after sorting.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
4 views3 pages
Dsa Thursday
The document contains a C program that implements linear search, bubble sort, and binary search algorithms. It demonstrates searching for a key in an unsorted array using linear search and then sorting the array before performing a binary search. The output confirms that the key was found at the same index in both search methods after sorting.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3
Dsa Thursday
#include <stdio.h>
// Function for linear search
int linearSearch(int arr[], int size, int key) { for (int i = 0; i < size; i++) { if (arr[i] == key) return i; } return -1; }
// Function to sort array using Bubble Sort
void bubbleSort(int arr[], int size) { for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
// Function for binary search
int binarySearch(int arr[], int size, int key) { int low = 0, high = size - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == key) return mid; else if (arr[mid] < key) low = mid + 1; else high = mid - 1; } return -1; }
int main() { int arr[] = {34, 7, 23, 32, 5, 62}; int size = sizeof(arr) / sizeof(arr[0]); int key = 23;
// Linear Search on unsorted array
int indexLinear = linearSearch(arr, size, key); if (indexLinear != -1) printf("Linear Search: %d found at index %d\n", key, indexLinear); else printf("Linear Search: %d not found\n", key);
// Sort the array
bubbleSort(arr, size);
// Binary Search on sorted array
int indexBinary = binarySearch(arr, size, key); if (indexBinary != -1) printf("Binary Search: %d found at index %d (in sorted array)\n", key, indexBinary); else printf("Binary Search: %d not found\n", key);
return 0; }
OUTPUT
Linear Search: 23 found at index 2
Binary Search: 23 found at index 2 (in sorted array)