Advertisement
codegod313

Biblioteka

Jun 29th, 2020
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. struct Book
  2. {
  3.     char* author;
  4.     char* name;
  5.     int year;
  6. };
  7.  
  8. void menu()
  9. {
  10.     printf("\n1: Добавить книгу\n");
  11.     printf("2: Сортировать библиотеку\n");
  12.     printf("3: Выход\n");
  13. }
  14.  
  15. int init_str(char * &s) {
  16.     int i = 0;
  17.     while ((s[i] = getchar()) != '\n') {
  18.         s = (char *)realloc(s, sizeof(char)*(i + 2));
  19.         if (!s)
  20.             exit(-1);
  21.         i++;
  22.     }
  23.     s[i] = '\0';
  24.     return i;
  25. }
  26.  
  27.  
  28. void add_book(Book* &books, int &count)
  29. {
  30.     if (books == NULL)
  31.         books = (Book*)malloc(sizeof(Book));
  32.     else
  33.     {
  34.         books = (Book*)realloc(books, count + 1);
  35.     }
  36.     count++;
  37.     printf("Введите название книги\n");
  38.     rewind(stdin);
  39.     books[count - 1].name = (char*)malloc(sizeof(char));
  40.     init_str(books[count - 1].name);
  41.     printf("Введите автора книги\n");
  42.     rewind(stdin);
  43.     books[count - 1].author = (char*)malloc(sizeof(char));
  44.     init_str(books[count - 1].author);
  45.     printf("Введите год\n");
  46.     while (!scanf("%d", &books[count - 1].year) || books[count - 1].year > 2020 || books[count - 1].year < 0)
  47.         rewind(stdin);
  48.  
  49. }
  50.  
  51. void sort_books(Book* &books, int b, int e)
  52. {
  53.     int l = b, r = e;
  54.     int piv = books[(l + r) / 2].year;
  55.     while (l <= r)
  56.     {
  57.         while (books[l].year < piv)
  58.             l++;
  59.         while (books[r].year > piv)
  60.             r--;
  61.         if (l <= r)
  62.         {
  63.             Book tmp = books[l];
  64.             books[l] = books[r];
  65.             books[r] = tmp;
  66.             l++;
  67.             r--;
  68.         }
  69.     }
  70.     if (b < r)
  71.         sort_books(books, b, r);
  72.     if (e > l)
  73.         sort_books(books, l, e);
  74.  
  75. }
  76.  
  77. int main()
  78. {
  79.     int choice;
  80.     Book* books = NULL;
  81.     int books_c = 0;
  82.     while (true)
  83.     {
  84.         system("CLS");
  85.         menu();
  86.         scanf("%d", &choice);
  87.         switch (choice)
  88.         {
  89.         case 1: add_book(books, books_c);
  90.             break;
  91.         case 2:
  92.             sort_books(books,0,books_c-1);
  93.             break;
  94.         default:
  95.             printf("Неправильный выбор\n");
  96.             break;
  97.         }
  98.     }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement