Write a C program to implement binary search using recursion.
#include <stdlib.h>
/* Performs binary search to find the search element "key" */
int binarySearching(int high, int low, int key, int entry[]) {
int middle, ret = -1;
if (low <= high) {
middle = (high + low) / 2;
/*
* if search element is greater than middle, then
* search the right part of the input array (entry). If
* the search element is lesser than the middle
* element, then search the left part of the input
* array.
*/
if (entry[middle] < key) {
low = middle + 1;
ret = binarySearching(high, low, key, entry);
} else if (entry[middle] > key) {
high = middle - 1;
ret = binarySearching(high, low, key, entry);
} else {
printf("Search element %d found "
"at index %d\n", key, middle + 1);
ret = 0;
}
}
return (ret);
}
int main() {
int *entry, n, i, j, tmp, search, ret;
/* get the number of entries from the user */
printf("Enter the number of entries:");
scanf("%d", &n);
/* dynamically allocate memory to store the entries */
entry = (int *)malloc(sizeof (int) * n);
/* get the entries from the user */
printf("Enter your input data:\n");
for (i = 0; i < n; i++)
scanf("%d", &entry[i]);
/* sort them in ascending order */
for (i = 0; i < n - 1; i++) {
tmp = entry[i];
for (j = i + 1; j < n; j++) {
if (tmp > entry[j]) {
tmp = entry[j];
entry[j] = entry[i];
entry[i] = tmp;
}
}
}
/* print the sorted entries */
for (i = 0; i < n; i++)
printf("%d ", entry[i]);
/* get the entry to be searched from user */
printf("\nEnter the entry to be searched:");
scanf("%d", &search);
/* do binary search to find the given data */
ret = binarySearching(n, 0, search, entry);
/* print the result */
if (ret == -1)
printf("Given key is not present\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of entries:5
Enter your input data:
100
50
70
500
250
50 70 100 250 500
Enter the entry to be searched:500
Search element 500 found at index 5
Enter the number of entries:5
Enter your input data:
100
50
70
500
250
50 70 100 250 500
Enter the entry to be searched:500
Search element 500 found at index 5
No comments:
Post a Comment