Created
March 11, 2015 01:22
-
-
Save 98chimp/52db263126a1f09500cd to your computer and use it in GitHub Desktop.
Binary Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.c | |
// Binary Search | |
// | |
// Created by Shahin on 2015-03-10. | |
// Copyright (c) 2015 98% Chimp. All rights reserved. | |
// | |
#include <stdio.h> | |
int binarySearch(int key, int array[], int min, int max) { | |
if (key < array[min] || key > array[max]) { | |
printf("the number you entered is not in the array"); | |
return -1; | |
} | |
else { | |
int middle = (min+max)/2; | |
if (key > array[middle]) { | |
return binarySearch(key, array, middle, max); | |
} | |
else if (key < array[middle]) { | |
return binarySearch(key, array, min, middle); | |
} | |
else { | |
return middle; | |
} | |
} | |
} | |
int main(int argc, const char * argv[]) { | |
int array[]= {1,2,5,9,38,48,89,99}; | |
int min = 0; | |
int max = 7; | |
int key; | |
printf("Enter the element to be found : "); | |
scanf("%d", &key); | |
int result = binarySearch(key, array, min, max) + 1; | |
printf("The result is in position %d", result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment