diff --git a/du2/program.c b/du2/program.c new file mode 100644 index 0000000..39ba6ab --- /dev/null +++ b/du2/program.c @@ -0,0 +1,57 @@ +#include +#include +#include + +#define LINE_SIZE 101 +#define LIST_SIZE 100 + +struct pizza { + char name[LINE_SIZE]; + float price; +}; + +int read_item(struct pizza *item) { + char buffer[LINE_SIZE]; + + if (fgets(buffer, LINE_SIZE, stdin) == NULL) return 0; + buffer[strcspn(buffer, "\n")] = '\0'; + + if (strlen(buffer) == 0) return 0; + strcpy(item->name, buffer); + + if (fgets(buffer, LINE_SIZE, stdin) == NULL) return 0; + return (sscanf(buffer, "%f", &item->price) == 1) ? 1 : 0; +} + +void swap(struct pizza *a, struct pizza *b) { + struct pizza tmp = *a; + *a = *b; + *b = tmp; +} + +void bubble_sort(struct pizza *menu, int count) { + for (int i = 0; i < count - 1; i++) { + for (int j = 0; j < count - i - 1; j++) { + int need_swap = (menu[j].price > menu[j + 1].price) ? 1 : + (menu[j].price < menu[j + 1].price) ? 0 : + (strcmp(menu[j].name, menu[j + 1].name) > 0 ? 1 : 0); + if (need_swap) swap(&menu[j], &menu[j + 1]); + } + } +} + +int main() { + struct pizza menu[LIST_SIZE]; + size_t count; + + for (count = 0; count < LIST_SIZE && read_item(&menu[count]); count++); + + bubble_sort(menu, (int)count); + + for (size_t i = 0; i < count; i++) { + puts(menu[i].name); + printf("%.6f\n", menu[i].price); + } + + return 0; +}