2010-05-04 58 views
2

此外,爲什麼這會給我一個錯誤,因爲我用布爾?順序搜索算法的問題

我需要使用這種順序搜索算法,但我真的不知道如何。我需要與數組一起使用它。有人可以指出我正確的方向或者如何使用它。

bool seqSearch (int list[], int last, int target, int* locn){ 
    int looker; 

    looker = 0; 
    while(looker < last && target != list[looker]){ 
        looker++; 
    } 

    *locn = looker; 
    return(target == list[looker]); 
} 
+0

我知道我需要傳遞數組和最後一個數組的大小,但我不知道要在target和int中放置什麼* locn – shinjuo 2010-05-04 06:18:46

回答

1

看起來你會使用這樣的......

// I assume you've set an int list[], an int listlen and an int intToFind 

int where; 
bool found = seqSearch(list, listlen - 1, intToFind, &where); 
if (found) 
{ 
    // list[where] is the entry that was found; do something with it 
} 
1

有幾個問題。

  1. 我會將last的名稱改爲size。
  2. 如果您未找到該值,則會取消引用無效的內存位置。

編輯:我想最後是length - 1。這是一個不尋常的簽名。所以電話是這樣的:

int list[CONSTANT]; 
... 
int foundIndex; 
bool found = seqSearch(list, sizeof(list)/sizeof(int), target, &foundIndex); 

有許多方法來啓用布爾。一種是在C99中使用stdbool.h

+0

這是直接出來的這本書。他說這可能是在最後,我想確保我知道如何使用它 – shinjuo 2010-05-04 06:21:26

+0

我同意2,但這是非常標準的C雖然,分配* locn存儲的責任是調用者 – hhafez 2010-05-04 06:23:08

+0

hhafez,我想我們都誤解了。 :)我認爲'last'是數組的長度(顯然是'length - 1'),所以它看起來像是數組可能被非法訪問後的元素。我不是在說「locn」。 – 2010-05-04 06:30:10

1

,很明顯

list[]是您正在搜索 last名單在list target的最後一個索引是你正在尋找在list locn將包含索引位置target發現 回報值是一個布爾值,指示是否發現target

對於你的問題如何傳遞locn,做類似

int locn; /* the locn where the index of target will be stored if found */ 

bool target_found = seqSearch(blah blah blah, &locn); 
+0

但是我通過什麼進入本地? – shinjuo 2010-05-04 06:22:52

+0

'int locn;/*如果找到目標索引的位置*/ bool target_found = seqSearch(等等等等等等,&locn);' – hhafez 2010-05-04 06:29:27

1

與您的代碼的問題是,如果你尋找不存在的數組中的元素,looker將等於last,並嘗試在位置last這是無效的訪問數組元素。

相反,你可以這樣做:

bool seqSearch (int list[], int last, int target, int* locn) { 

    int looker; 

    for(looker=0;looker<last;looker++) { 

     // target found. 
     if(list[looker] == target) { 
      *locn = looker; // copy location. 
      return true; // return true. 
     } 
    } 

    // target not found. 
    *locn = -1; // copy an invalid location. 
    return false; // return false. 
} 

你調用該函數如下:

int list[] = {5,4,3,2,1}; // the array to search in. 
int size = sizeof(list)/sizeof(list[0]); // number of elements in the array. 
int target = 3; // the key to search for. 
int locn; // to hold the location of the key found..and -1 if not found. 

if(seqSearch(list,size,target,&locn)) { 
    // target found in list at location locn. 
} else { 
    // target not found in list. 
} 
+0

你怎麼知道'last'不在數組中?你可以通過'last'的長度爲1,然後它的功能就好了,我認爲'last'在這裏只是指它是你應該檢查的最後一個地方(如果你只想檢查數組的一部分),那麼提供正確的端點的責任落在調用者上 – MBennett 2010-05-04 06:32:11

+0

我正在嘗試這樣做,但它給我一個使用bool的錯誤 – shinjuo 2010-05-04 06:41:54

+1

@shinjuo:你需要在這裏包含'stdbool.h'這是一個工作示例: http://www.ideone.com/pWmTx – codaddict 2010-05-04 06:49:29