2011-09-10 24 views
1

我正在嘗試通過修改的二進制搜索來查找排序數組中的旋轉點。在排序數組中查找旋轉點

考慮這個陣列int values[9]={7, 8, 9, 1, 2, 3, 4, 5, 6}; 旋轉點在這裏是在索引= 3即在9

我寫這個功能對於上述操作。

void FindRotationPoint(int values[], int numvalues) 
{ 
    int first =0; 
    int last = numvalues-1; 
    int middle; 
    bool moreTosearch= (first<=last); 
    while(first<=last) 
    { 
     middle = (first+last)/2; 
     if(values[0]>values[middle]) //Keep looking right if the middle value in array is greater than first 
     { 
      last = middle-1; 
     } 
     if (values[0]<values[middle]) //Keep looking left if the middle value in array is less than first 
     { 
      first = middle+1; 
     } 
    } 
    cout<<middle+1<<endl; 
    cout<<values[middle]; 
} 

如果元素是 int values[9]={7, 8, 9, 1, 2, 3, 4, 5, 6};輸出:4,1(錯)

int values[9]={7, 8, 9, 10, 2, 3, 4, 5, 6};輸出:4,10(正確)

旋轉的點,這是在一個甚至找到正確的地方,而在另一種情況下,它找到了後續的元素。在上面的代碼中我缺少什麼?

+0

由於moreTosearch永遠只是(拳頭<=最後的),也許你應該將其刪除,並把第一<=最後在while條件。這將使事情更加緊湊,更易於閱讀。 – quasiverse

+0

此外,如果有重複的元素,這可能無法正常工作。 – quasiverse

+3

9位於索引2,不是3. – ildjarn

回答

0

這工作:

void FindRotationPoint(int values[], int numvalues) 
{ 
    int first =0; 
    int last = numvalues-1; 
    int middle=0; 
    bool moreTosearch= (first<=last); 
    while(first<last) 
    { 
     middle = (first+last)/2; 
     if(values[first]>=values[middle]) //Keep looking right if the middle value in array is greater than first 
     { 
      last = middle; 
      cout<<"first>middle: "<<first<<" "<<middle<<" "<<last<<"\n"; 
     } 
     else if (values[middle]>=values[last]) //Keep looking left if the middle value in array is less than first 
     { 
      first = middle; 
      cout<<"middle<last: "<<first<<" "<<middle<<" "<<last<<"\n"; 
     } 
    } 
    cout<<middle+1<<endl; 
    cout<<values[middle]; 
} 

int main() 
{ 
int values[9]={7, 8, 9, 1, 2, 3, 4, 5, 6}; 

FindRotationPoint(values, 9); 
return 0; 
} 
+0

它只適用於包含一個元素的數組嗎? – Raj

+0

你可能已經嘗試過,並詢問它是否不適合你。 –

+0

該代碼有一個錯誤。它不適用於{1,2,3,4};並且還用於{1,1,1,0,1,1,1,1,1,1,1}。 –

0
void FindRotationPoint(int values[], int numvalues) 
{ 
    int first =0; 
    int last = numvalues-1; 
    int middle; 
    bool moreTosearch= (first<=last); 
    while(moreTosearch) 
    { 
     middle = (first+last)/2; 
     if(middle == first) break; 
     if(values[0]>values[middle]) //Keep looking right if the middle value in array is greater than first 
     { 
      last = middle; 
      moreTosearch= (first<=last); 
     } 
     if (values[0]<values[middle]) //Keep looking left if the middle value in array is less than first 
     { 
      first = middle; 
      moreTosearch= (first<=last); 
     } 
    } 
} 

這應該工作。

+0

在輸入'int values [9] = {7,8,9,10,2,3,4,5,6}處使用此數組;'' 輸出結果爲3,9,這不是正確的答案。 – Cipher

+0

再次檢查:: 3,9爲情況1和4,10爲情況2。它的工作! –

+0

呃...是啊!這是工作。我沒有注意到其他變化。你能解釋爲什麼'last = middle','first = middle'和'if(middle = first)break;'完成了嗎? – Cipher