From b26f1e1d3f4f6d1988479d1b548a425babaef184 Mon Sep 17 00:00:00 2001 From: Raman1309 <40718728+Raman1309@users.noreply.github.com> Date: Fri, 25 Oct 2019 19:43:53 +0530 Subject: [PATCH] BinarySearch.c Binary Search implementation using Recursive and Iterative Method according to the user's choice. --- BinarySearch.c | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 BinarySearch.c diff --git a/BinarySearch.c b/BinarySearch.c new file mode 100644 index 00000000..9305d09e --- /dev/null +++ b/BinarySearch.c @@ -0,0 +1,68 @@ +#include + +//Recursive Method +int binarySearchR(int arr[], int l, int r, int x) +{ + if (r >= l) { + int mid = l + (r - l) / 2; + + if (arr[mid] == x) + return mid; + + if (arr[mid] > x) + return binarySearchR(arr, l, mid - 1, x); + + return binarySearchR(arr, mid + 1, r, x); + } + + return -1; +} + +//Iterative Method +int binarySearchI(int arr[], int l, int r, int x) +{ + while (l <= r) { + int m = l + (r - l) / 2; + + if (arr[m] == x) + return m; + + if (arr[m] < x) + l = m + 1; + + else + r = m - 1; + } + + return -1; +} + +int main(void) +{ + int n; + printf("Size : "); + scanf("%d",&n); + + int arr[n]; + + for(int i=0;i