diff --git a/C/BinarySearch.c b/C/BinarySearch.c new file mode 100644 index 0000000..b5e7654 --- /dev/null +++ b/C/BinarySearch.c @@ -0,0 +1,45 @@ +/* Binary Search Algorithm : + (i) Binary search is more efficient but works only on sorted arrays. + (ii) It divides the array in half and eliminates half of the remaining elements with each comparison. + + Problem Statement : To check if number is present in the array or not using binary search + Test Case : 10, 23, 45, 70, 75, 80 + Target : 70 + Output : Element found at index 3 +*/ + + +#include + +// This is binary serach algorithm's main logic +int binarySearch(int arr[], int size, int key) { + int low = 0, high = size - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; // FInd the middle of the array + + if (arr[mid] == key) { // Check if middle is equal to target + return mid; + } else if (arr[mid] < key) { // Check if middle is less than target + low = mid + 1; + } else { // if middle is greater than target + high = mid - 1; + } + } + return -1; +} + +int main() { + int arr[] = {10, 23, 45, 70, 75, 80}; + int size = sizeof(arr) / sizeof(arr[0]); + int key = 70; + + int result = binarySearch(arr, size, key); + if (result == -1) { + printf("Element not found\n"); + } else { + printf("Element found at index %d\n", result); + } + + return 0; +} \ No newline at end of file diff --git a/C/LinearSearch.c b/C/LinearSearch.c new file mode 100644 index 0000000..187be0e --- /dev/null +++ b/C/LinearSearch.c @@ -0,0 +1,36 @@ +/* Linear Search Algorithm : + (i) This is the simplest searching algorithm. + (ii) It checks each element of the array until the desired element is found. + + Problem Statement : To check if number is present in the array or not using linear search + Test Case : 81, 23, 45, 30, 70, 11, 15 + Target : 70 + Output : Element found at index 4 +*/ + +#include + +// This is linear serach algorithm's main logic +int linearSearch(int arr[], int size, int key) { + for (int i = 0; i < size; i++) { + if (arr[i] == key) { + return i; + } + } + return -1; +} + +int main() { + int arr[] = {81, 23, 45, 30, 70, 11, 15}; + int size = sizeof(arr) / sizeof(arr[0]); + int key = 70; + + int result = linearSearch(arr, size, key); + if (result == -1) { + printf("Element not found\n"); + } else { + printf("Element found at index %d\n", result); + } + + return 0; +}