Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search Algorithms in C #285

Merged
merged 1 commit into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}