Advertisement
PillTime

Binary Search com strings

Feb 19th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. // Binary Search
  2.  
  3. // signed char = inteiro de -128 a 127
  4. // unsigned char = inteiro de 0 a 255
  5.  
  6. #include <stdio.h>
  7. #include <string.h>
  8.  
  9. #define ARRAY_SIZE      10
  10. #define MAX_STRING_SIZE 20
  11.  
  12. signed char binarySearch(char a[][MAX_STRING_SIZE], unsigned char l, unsigned char r, char x[MAX_STRING_SIZE]) {
  13.  
  14.     // Nome não foi encontrado
  15.     if (l > r)
  16.         return -1;
  17.  
  18.     // Procurar numa área
  19.     else {
  20.  
  21.         // Obter índice do meio da área
  22.         unsigned char m = (r-l)/2 + l;
  23.  
  24.         // Retornar índice se for o nome procurado
  25.         if (!strcmp(a[m], x)) // true se a[m] e x forem iguais
  26.             return m;
  27.  
  28.         // Procurar na área onde o nome deve estar
  29.         else
  30.             if (strcmp(a[m], x) > 0)
  31.                 return binarySearch(a, l, m-1, x);
  32.             else
  33.                 return binarySearch(a, m+1, r, x);
  34.     }
  35. }
  36.  
  37. int main(void) {
  38.  
  39.     // Criar o array onde procurar
  40.     char array[ARRAY_SIZE][MAX_STRING_SIZE] = {
  41.         "Ana",
  42.         "Bruno",
  43.         "Carlos",
  44.         "Daniela",
  45.         "Frederico",
  46.         "Inês",
  47.         "Joana",
  48.         "Mário",
  49.         "Teresa",
  50.         "Vasco"
  51.     };
  52.  
  53.     // Receber o nome a procurar
  54.     char search[MAX_STRING_SIZE];
  55.     printf("\n Indique o nome a procurar: "); fflush(stdout); // fflush = certificar q faz print
  56.     scanf("%s", search);
  57.  
  58.     // Receber o índice de onde o nome está
  59.     signed char index = binarySearch(array, 0, ARRAY_SIZE-1, search);
  60.  
  61.     // Indicar o índice ao user
  62.     if (index == -1)
  63.         printf("\n Erro! Nome não encontrado no array!\n\n");
  64.     else
  65.         printf("\n O nome pedido está no índice %hhu do array.\n\n", index);
  66.  
  67.     // Terminar
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement