4
Dichoto
- #include <iostream>
- using namespace std;
- void search( int &found, int &index, int tab[], const int siz, int val )
- {
- int left = 0, right = siz-1;
- found = 0;
- while ( left <= right ) {
- index = (left + right) / 2;
- found = (tab[ index ] == val);
- if ( found )
- break;
- if ( tab[ index ] < val )
- left = index+1;
- else
- right = index-1;
- }
- }
- int main() {
- int tab[ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
- int siz = sizeof (tab) / sizeof (int);
- int val, found, index;
- for ( ;; ) { // forever
- cout << "Enter a value (1-9) or 0 to exit: ";
- cin >> val;
- if ( val == 0 )
- break;
- search( found, index, tab, siz, val );
- if ( found )
- cout << "tab[ " << index << " ]=" << val << endl;
- }
- }
Commentaires