7

Dichoto

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. void search( int &found, int &index, int tab[], const int siz, int val )
  6. {
  7.     int left = 0, right = siz-1;
  8.     found = 0;
  9.  
  10.     while ( left <= right ) {
  11.         index = (left + right) / 2;
  12.         found = (tab[ index ] == val);
  13.         if ( found )
  14.             break;
  15.         if ( tab[ index ] < val )
  16.             left = index+1;
  17.         else
  18.             right = index-1;
  19.     }
  20. }
  21.  
  22. int main() {
  23.     int tab[ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  24.     int siz = sizeof (tab) / sizeof (int);
  25.     int val, found, index;
  26.  
  27.     for ( ;; ) {    // forever
  28.         cout << "Enter a value (1-9) or 0 to exit: ";
  29.         cin >> val;
  30.         if ( val == 0 )
  31.             break;
  32.         search( found, index, tab, siz, val );
  33.         if ( found )
  34.             cout << "tab[ " << index << " ]=" << val << endl;
  35.     }
  36. }

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].