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

Program 5 Binary Search

Uploaded by

sanamzuneriya759
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)
5 views

Program 5 Binary Search

Uploaded by

sanamzuneriya759
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/ 1

Program 5: Write a C Program to Sort the given set of N numbers using Bubble sort and

implement Binary Search on sorted Integers.


#include <stdio.h>
int main() {
// Declare variables
int n, key, found, left, right, mid, i, j;
// Input number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Declare array
int A[n]; // Dynamic array based on user input
// Input elements
printf("Enter the elements:\n");
for (i = 0; i < n; i++) {
scanf("%d", &A[i]);
}
// Bubble Sort
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (A[j] > A[j + 1]) {
// Swap A[j] and A[j + 1]
int temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
} } }
// Print sorted array
printf("Sorted array: ");
for (i = 0; i < n; i++) {
printf("%d ", A[i]);
}
printf("\n");
// Input key element to search
printf("Enter the element to search: ");
scanf("%d", &key);
// Initialize Binary Search variables
left = 0;
right = n - 1;
found = -1;
// Binary Search
while (left <= right) {
mid = left + (right - left) / 2;
if (A[mid] == key) {
found = mid; // Key found
break;
} else if (A[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
} }
// Display search result
if (found != -1) {
printf("Element %d found at position %d.\n", key, found);
} else {
printf("Element %d not found in the array.\n", key);
}
return 0;
}

You might also like