/*広告*/
/*[C言語]サンプルプログラム集 2分探索法ソース2*/
#include <stdio.h> int my_binary(int* ,int,int,int); int main(){ int ary[10] = {5,7,13,18,27,32,38,52,60,78}; int target = 52; int result = 0; int j = 0; result = my_binary(ary,target,0,9); printf("配列の内容\n"); for(j=0;j<10;j++){ printf("[%d]",ary[j]); } printf("\n\n探す数字 = %d\n\n",target); if(result == -1){ printf("見つかりませんでした!\n"); } else{ printf("添え字番号%d番目で見つかりました!\n",result); } return 0; } int my_binary(int* ary,int target,int index_head,int index_tail){ int center = (index_head + index_tail) / 2; while(1){ if(*(ary + center) == target || index_head > index_tail){ break; } else if(*(ary + center) < target){ index_head = center + 1; } else{ index_tail = center - 1; } center = (index_head + index_tail) / 2; } if(index_head > index_tail){ return -1; } else{ return center; } }/*Copyright 2016 K.N/petitetech.com*/
/*広告*/