0

## C語言if改用while覺得沒信心

Tzu 2021-01-10 09:48:571214 瀏覽

DEAR 各位大大早安

``````
/*if(low > high)
return -1;
else{
middle = (low+high) /2;
if(target == data[middle])
return middle;
else if (target<data[middle])
return binary(data,low,middle-1,target);
else
return binary(data,middle+1,high,target);
}*/

``````

``````	while(low > high){
return -1;
}

``````

Tzu iT邦新手 5 級 ‧ 2021-01-10 09:50:16 檢舉

````
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 11

int binary(int*data,int low,int high,int target){
int middle;

while(low > high){
return -1;
}

/*if(low > high)
return -1;
else{
middle = (low+high) /2;
if(target == data[middle])
return middle;
else if (target<data[middle])
return binary(data,low,middle-1,target);
else
return binary(data,middle+1,high,target);
}*/

}

int main(){
int data[MAX_LEN]=
{1,8,9,15,25,33,42,66,74,81,90};
int i,index,target,c;
printf("原始陣列:");
for (i = 0 ; i < MAX_LEN ; i++ )
printf("[%d]",data[i]);
printf("\n");
target=0;
while (target !=-1){
printf("請輸入搜尋值(-1結束)==>");
scanf("%d",&target);
index=binary(data,0,MAX_LEN-1,target);
if(index !=-1)
printf("搜尋到鍵值:%d(%d)\n",target,index);
else
printf("沒有搜尋到鍵值:%d\n",target);

}

return 0;
}

````

### 2 個回答

1

iT邦新手 4 級 ‧ 2021-01-10 16:17:08

1. 創建數字陣列
2. 獲取使用者輸入的值
3. 查找陣列中該值的位置
4. 找到回傳 index
5. 找不到回傳 -1

if 是流程控制中的選擇敘述
while 是流程控制中的重複敘述

``````int binary(int* data, int low, int high, int target) {
while(low <= high){
if(data[low] == target) {
return low;
}
low++;
}
return -1;
}
``````

``````int binary(int* data, int low, int high, int target) {
int middle = (low + high) / 2;
do {
if(target == data[middle])
return middle;
else if (target < data[middle])
high = middle - 1;
else
low = middle + 1;
middle = (low + high) / 2;
} while (low <= high);
return -1;
}
``````

Tzu iT邦新手 5 級 ‧ 2021-01-10 21:55:47 檢舉

0
0427ryan
iT邦新手 5 級 ‧ 2021-01-10 16:55:19

``````int binary(int* data, int low, int high, int target){
while(low <= high){
int middle = (low + high) / 2;
if(target == data[middle]){ // middle就是目標的索引
return middle;
}
if (target < data[middle]){ // target比中間值小 -> 減少high
high = middle - 1;
}
else{                       // target 比中間值大 -> 增加low
low = middle + 1;
}
}

return -1;                      // low < high
}
``````

ps有排版看起來應該會清楚點

Tzu iT邦新手 5 級 ‧ 2021-01-10 21:55:32 檢舉

0427ryan iT邦新手 5 級 ‧ 2021-01-11 17:51:11 檢舉