acobzew

sem3-problem4

Apr 10th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include <string.h>
  5.  
  6. #define MAX_DATABASE_SIZE 100
  7. #define MAX_STR_LEN 30
  8.  
  9.  
  10. void getstr(char s[]) {
  11.     char c;
  12.     int i = 0;
  13.     while((c = getchar()) != '\n')
  14.         s[i++] = c;
  15.     s[i] = '\0';
  16. }
  17.  
  18. bool binSearch(char s[], char **database, int databaseSize) {
  19.     int l = 0, r = databaseSize, m;
  20.     int cmp;
  21.     while (l < r) {
  22.         m = l + (r - l) / 2;
  23.         cmp = strcmp(s, database[m]);
  24.         if (cmp <= 0)
  25.             r = m;
  26.         else
  27.             l = m + 1;
  28.     }
  29.  
  30.     return (r < databaseSize && strcmp(s, database[r]) == 0);
  31. }
  32.  
  33. int main() {
  34.     FILE *file = fopen("database.txt", "r");
  35.  
  36.     int i = 0, j = 0, databaseSize = 0;
  37.     char c;
  38.     char **database = (char **)malloc(MAX_DATABASE_SIZE * sizeof(char *));
  39.     bool finish = false;
  40.    
  41.     for (i = 0; i < MAX_DATABASE_SIZE && !finish; i++) {
  42.         database[i] = (char *)malloc(MAX_STR_LEN * sizeof(char));
  43.        
  44.         j = 0;
  45.         while ((c = fgetc(file)) != '\n' && c != EOF)
  46.             database[i][j++] = c;
  47.        
  48.         finish = (j == 0);
  49.     }
  50.     databaseSize = i - 1;
  51.     fclose(file);
  52.  
  53.     char s[MAX_STR_LEN];
  54.     getstr(s);
  55.     if (binSearch(s, database, databaseSize))
  56.         printf("Found!");
  57.     else
  58.         printf("Not found!");
  59.  
  60.  
  61.     for (i = 0; i < databaseSize; i++)
  62.         free(database[i]);
  63.     free(database);
  64.  
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment