komediruzecki

Untitled

May 6th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<malloc.h>
  4. #include<stdlib.h>
  5.  
  6. #define MAX_NAME 50
  7.  
  8.  
  9. typedef struct {
  10.     int item_num;
  11.     char item_name[MAX_NAME + 1];
  12. } structure;
  13.  
  14.  
  15.  
  16. void printing_bubble(structure *A, int size) {
  17.     int c = 0;
  18.    
  19.     printf("\nThis are your items: ");
  20.  
  21.     for (c = 0; c < size; c++) {
  22.         printf("%d %s \n", A[c].item_num, A[c].item_name);
  23.     }
  24.  
  25. }
  26.  
  27. void simple_bubble_sort(structure *A, int size) {
  28.     int i = 0, j = 0;
  29.     structure temp;
  30.    
  31.  
  32.  
  33.     for (i = 0; i < size - 1; i++) {
  34.         for (j = 0; j < size - 1 - i; j++){
  35.             if (A[j].item_num > A[j + 1].item_num) {
  36.                 temp = A[j];
  37.                 A[j] = A[j + 1];
  38.                 A[j + 1] = temp;
  39.             }
  40.         }
  41.     }
  42.  
  43. }
  44.  
  45.  
  46.  
  47. int main(void) {
  48.  
  49.  
  50.     structure *one_item = NULL;
  51.     int num_of_items = 0;
  52.     int allocated = 1;
  53.     int i = 0, exit = 1;
  54.     structure *temp = NULL;
  55.  
  56.  
  57.  
  58.     one_item = malloc(allocated * sizeof(structure));
  59.     if (one_item == NULL) {
  60.         printf("Malloc failed");
  61.     }
  62.  
  63.     do {
  64.         printf("Type \"0\" to exit: ");
  65.         scanf("%d", &exit);
  66.         if (exit == 0) {
  67.             break;
  68.         }
  69.  
  70.         printf("Type in your %d item serial number: ", num_of_items + 1);
  71.         scanf("%d", &one_item[i].item_num);
  72.  
  73.         printf("Type in your product name: ");
  74.         scanf(" %[^\n]", one_item[i].item_name);
  75.  
  76.         num_of_items += 1;
  77.  
  78.         if (num_of_items >= allocated) {
  79.             temp = realloc(one_item, allocated * 2 * sizeof(structure));
  80.                 if (temp != NULL) {
  81.                     one_item = temp;
  82.                     allocated *= 2;
  83.                 }
  84.                 else {
  85.                     printf("Allocation failed!");
  86.                 }
  87.         }
  88.  
  89.     } while (num_of_items < 10);
  90.  
  91.     printf("\nBefore sorting:\n ");
  92.     printing_bubble(one_item, num_of_items);
  93.  
  94.     simple_bubble_sort(one_item, num_of_items);
  95.  
  96.     printf("\nAfter sorting: \n");
  97.     printing_bubble(one_item, num_of_items);
  98.  
  99.     return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment