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

Added c code for binary search #88

Closed
wants to merge 2 commits into from
Closed
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ This repository contains examples of various algorithms written on different pro
| [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) | [:octocat:](insertion_sort/C) | | | [:octocat:](insertion_sort/Python) |
| [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) | | | | [:octocat:](counting_sort/Python) |
| [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | | | [:octocat:](radix_sort/Python) |
| [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) | | | | [:octocat:](binary_search/Python) |
| [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm)| | [:octocat:](binary_search/C) | | |[:octocat:](binary_search/Python) |
| [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | | [:octocat:](bubble_sort/C++) | | |



## Implemented Data Structures

| Data Structure | C | CPP | Java | Python |
Expand Down
28 changes: 28 additions & 0 deletions binary_search/C/binary_search.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

#include <stdio.h>
int binarySearch(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 binarySearch(arr, l, mid-1, x);
return binarySearch(arr, mid+1, r, x);
}
return -1;
}
int main(void)
{
int arr[] = {1, 3, 4, 16, 47};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 47;
int result = binarySearch(arr, 0, n-1, x);
if(result==-1)
printf("Element is not present in array");
else
printf("Element is present at index %d",result);

return 0;
}