Advertisement
cd62131

Insert Sort on Struct

Dec 5th, 2013
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.36 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct {
  4.   unsigned char *pref_name;
  5.   unsigned int poplation;
  6. } pref_t;
  7.  
  8. static pref_t *init_pref(void) {
  9.   pref_t *p = (pref_t *) malloc(sizeof(pref_t));
  10.   p->pref_name = (unsigned char *) malloc(BUFSIZ);
  11.   return p;
  12. }
  13.  
  14. static void print_pref(pref_t **data, size_t len) {
  15.   for (int i = 0; i < len; i++) {
  16.     printf("%s %d\n", data[i]->pref_name, data[i]->poplation);
  17.   }
  18. }
  19.  
  20. static void insert_sort_pref(pref_t **data, size_t len) {
  21.   for (int i = 1; i < len; i++) {
  22.     pref_t *p = data[i];
  23.     if (data[i - 1]->poplation > p->poplation) {
  24.       int j = i;
  25.       do {
  26.         data[j] = data[j - 1];
  27.         j--;
  28.       } while (j > 0 && data[j - 1]->poplation > p->poplation);
  29.       data[j] = p;
  30.     }
  31.   }
  32. }
  33.  
  34. int main(int argc, char **argv) {
  35.   FILE *in;
  36.   if (argc > 1) in = fopen(argv[1], "r");
  37.   else in = stdin;
  38.   char header[BUFSIZ];
  39.   fgets(header, BUFSIZ, in); // ignore header
  40.   pref_t *data[BUFSIZ];
  41.   size_t len = 0;
  42.   for (int i = 0; i < BUFSIZ; i++) {
  43.     data[i] = init_pref();
  44.     if (fscanf(in, "%s%d", data[i]->pref_name, &(data[i]->poplation)) == EOF) {
  45.       len = i;
  46.       break;
  47.     }
  48.   }
  49.   fclose(in);
  50.   printf("Before:\n");
  51.   print_pref(data, len);
  52.   printf("\n");
  53.   insert_sort_pref(data, len);
  54.   printf("After:\n");
  55.   print_pref(data, len);
  56.   return EXIT_SUCCESS;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement