Skip to content

Commit

Permalink
Search Algorithms in C (#285)
Browse files Browse the repository at this point in the history
  • Loading branch information
Sahil-xyz authored Oct 3, 2024
1 parent ea4ef9e commit 701636e
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
45 changes: 45 additions & 0 deletions C/BinarySearch.c
Original file line number Diff line number Diff line change
@@ -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 <stdio.h>

// 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;
}
36 changes: 36 additions & 0 deletions C/LinearSearch.c
Original file line number Diff line number Diff line change
@@ -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 <stdio.h>

// 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;
}

0 comments on commit 701636e

Please sign in to comment.