/*広告*/

/*[C言語]サンプルプログラム集 2分探索法ソース3*/

/*目次へ戻る*/

#include <stdio.h> struct STUDENT{ char name[128]; int score; }; int my_binary2(struct STUDENT* ,int,int,int); int main(){ int result = 0; int target = 52; int j = 0; struct STUDENT student[10] = { {"tanaka",5}, {"suzuki",7}, {"satou",13}, {"saitou",18}, {"watanabe",27}, {"aoki",32}, {"inoue",38}, {"koike",52}, {"wada",60}, {"ueno",78}, }; result = my_binary2(student,target,0,9); printf("配列の内容\n"); for(j=0;j<10;j++){ printf("名前 %s:得点 %d\n",student[j].name,student[j].score); } printf("\n探す対象 = %d\n\n",target); if(result == -1){ printf("見つかりませんでした!\n"); } else{ printf("添え字番号%d番目で見つかりました!\n",result); printf("名前 %s:得点 %d\n",student[result].name,student[result].score); } return 0; } int my_binary2(struct STUDENT* ary,int target,int index_head,int index_tail){ int center = (index_head + index_tail) / 2; while(1){ if((ary + center)->score == target || index_head > index_tail){ break; } else if((ary + center)->score < 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; } }

/*ページの先頭へ*/

/*目次へ戻る*/

/*HOME*/

/*Copyright 2016 K.N/petitetech.com*/

/*広告*/