0% found this document useful (0 votes)
12 views2 pages

Aoa Exp4

This document contains a C program that implements a binary search algorithm. It prompts the user to input a sorted array and a key to search for, then uses the binary search function to find the index of the key. The program outputs whether the element was found and its index, or indicates that the element is not in the array.

Uploaded by

Shrishti Tiwari
Copyright
© © All Rights Reserved
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% found this document useful (0 votes)
12 views2 pages

Aoa Exp4

This document contains a C program that implements a binary search algorithm. It prompts the user to input a sorted array and a key to search for, then uses the binary search function to find the index of the key. The program outputs whether the element was found and its index, or indicates that the element is not in the array.

Uploaded by

Shrishti Tiwari
Copyright
© © All Rights Reserved
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/ 2

AOA.

EXP4-
#include <stdio.h>

// Function to perform binary search


int binarySearch(int arr[], int left, int right, int key) {
if (left <= right) {
int mid = left + (right - left) / 2;

// Check if the key is at mid


if (arr[mid] == key)
return mid;

// If the key is smaller than mid, search in the left subarray


if (key < arr[mid])
return binarySearch(arr, left, mid - 1, key);

// Otherwise, search in the right subarray


return binarySearch(arr, mid + 1, right, key);
}

// If the element is not present in the array


return -1;
}

int main() {
int n, key;

// Input the number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n];

// Input the sorted array


printf("Enter %d elements in sorted order:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Input the element to be searched


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

// Call binarySearch function


int result = binarySearch(arr, 0, n - 1, key);

// Output the result


if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found in the array\n");

return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy