Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 8th, 2012  |  syntax: C  |  size: 1.18 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define MAX 12
  5.  
  6. int busca_binaria(int vetor[], int n, int k)
  7. {
  8.     int min=0, max = n-1, med, i;
  9.  
  10.  
  11.         while(min <= max)
  12.         {
  13.             med = (min + max) /2;       /* cálculo da posição média */
  14.  
  15.                 if(k == vetor[med])
  16.                     return med;         /* pesquisa com sucesso! Achou o numero! */
  17.                 if(k < vetor[med])
  18.                     max = med -1;       /* atualiza os limites do intervalo de pesquisa */
  19.                 else
  20.                     min = med +1;
  21.  
  22.                 printf("\n%d", med);
  23.         }
  24.  
  25.     return -1;                          /*Falha na pesquisa */
  26. }
  27.  
  28.  
  29. int main()
  30. {
  31.  
  32.     int vetor[] = {1,3,4,6,7,9,11,36,42, 49, 52, 60};
  33.     int i, pesq;
  34.  
  35.     for(i=0;i<MAX;i++)
  36.     {
  37.         printf("\nPosicao %d do vetor: %d ", i, vetor[i]);
  38.  
  39.     }
  40.  
  41.  
  42.     printf("\n\n\nNumero para pesquisar no vetor: ");
  43.     scanf("%d", &pesq);
  44.  
  45.     int posicao = busca_binaria(vetor, MAX, pesq);
  46.  
  47.         if (posicao == -1)
  48.             printf("\n NAO ENCONTRADO");
  49.  
  50.         else
  51.             printf("\n\nEncontrado na posicao %d do vetor!!", posicao);
  52.  
  53.     getch();
  54. }