IGNOU BCSL-033-Data and File Structures Lab, Latest Solved Assignment (July 2023 - January 2024 )
Q6. Write a program in C to search an input data from a set of data, stored in an array using binary search algorithm. Also, print the number of comparison operations performed for searching the given data.
Ans.
#include <stdio.h>
int binary_search(int arr[], int low, int high, int x) {
if (high >= low) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
return binary_search(arr, low, mid – 1, x);
} else {
return binary_search(arr, mid + 1, high, x);
}
}
return -1;
}
int main() {
int n, x, i, comparisons = 0;
printf(“Enter the number of elements: “);
scanf(“%d”, &n);
int arr[n];
printf(“Enter the elements: “);
for (i = 0; i < n; i++) {
scanf(“%d”, &arr[i]);
}
printf(“Enter the element to be searched: “);
scanf(“%d”, &x);
int index = binary_search(arr, 0, n – 1, x);
if (index != -1) {
printf(“Element found at index %d\n”, index);
} else {
printf(“Element not found\n”);
}
// Calculating number of comparisons
for (i = 0; i < n – 1; i++) {
for (int j = i + 1; j < n; j++) {
comparisons++;
}
}
printf(“Number of comparisons = %d\n”, comparisons);
return 0;
}
Assignment Submission Last Date
The IGNOU open learning format requires students to submit study Assignments. Here is the final end date of the submission of this particular assignment according to the university calendar.
30th April (if Enrolled in the June Exams)
31st October (if Enrolled in the December Exams)