반응형
BinarySearch.h
- #ifndef __BINARYSEARCH_H__
- #define __BINARYSEARCH_H__
- #define FAIL -1
- int binarySearch_Recursive(int value[], int start, int end, int data);
- int binarySearch(int value[], int start, int end, int data);
- #endif
BinarySearch.c
- #include<stdio.h>
- #include"BinarySearch.h"
- //Using Recursive
- int binarySearch_Recursive(int value[], int start, int end, int data)
- {
- int ret=FAIL;
- int middle;
- if(start <= end)
- {
- middle = (start + end)/2;
- if(value[middle] == data)
- {
- ret = middle;
- }
- else if(value[middle] < data)
- {
- ret = binarySearch(value, middle+1, end, data);
- }
- else
- {
- ret = binarySearch(value, start, middle-1, data);
- }
- return ret;
- }
- }
- //Using Recursive
- int binarySearch(int value[], int start, int end, int data)
- {
- int ret=FAIL;
- int middle;
- while(start <= end)
- {
- middle = (start + end)/2;
- if(value[middle] == data)
- {
- ret=middle;
- break;
- }
- else if(value[middle] < data)
- {
- start = middle+1;
- }
- else
- {
- end = middle-1;
- }
- }
- return ret;
- }
test.c
- #include<stdio.h>
- #include"BinarySearch.h"
- int main()
- {
- int value[10]={10,20,30,40,50,60,70,80,90,100};
- return 0;
- }
반응형
'ETC > Data Struct | Algorithm' 카테고리의 다른 글
[STL] algorithm 내부 sort 함수의 원형 (0) | 2015.04.01 |
---|---|
Graph - 인접 행렬 그래프 (0) | 2014.06.25 |
순차 검색 (Sequential Search) (0) | 2014.05.15 |
이진트리 순회 (0) | 2013.05.01 |
이진트리 (0) | 2013.04.30 |