contrib/newshound/sort.c

/* [<][>]
[^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following functions.
  1. swap
  2. compare
  3. shell_sort
  4. file_array
  5. sortit

/* sort.c routines */

#include "conf.h"

int entries;
char **list;
FILE *sp;
typedef char *Data_type;

void swap(Data_type *a, Data_type *b) /* swap(&s1, &s2); */
/* [<][>][^][v][top][bottom][index][help] */
  {
   Data_type temp;

   temp = *a;
   *a = *b;
   *b = temp;
  }

int compare(char *s1, char *s2) /* We sort and sort but do it decending */
/* [<][>][^][v][top][bottom][index][help] */
  {
   return(strcmp(s2, s1));
  }

void shell_sort(Data_type d[], int size)
/* [<][>][^][v][top][bottom][index][help] */
  {
   int i, start, gap;

   if (debug>=1) printf("Sorting array.\n");
   for(gap = size/2; gap > 0; gap/=2)
     for(start = 0; start < size - gap; start++)
       for(i=start; i>=0 && compare(d[i], d[i+gap])>0; i-=gap)
         swap(&d[i], &d[i+gap]);
  }

int file_array(char *file)
/* [<][>][^][v][top][bottom][index][help] */
  {
   int i=0;
   char buf[128];

   entries=0;

   sp=fopen(file, "r");
   
   while (fgets(buf, 128, sp) != NULL) ++entries;
   if (debug>=1) printf("File :- %s has %d lines.\n", file, entries);
   
   list = (char **)malloc(entries*sizeof(buf));
   if (list == NULL)
     {
      fprintf(stderr, "Couldn't malloc memory for file array.\n");
      exit (1);
     }

   rewind(sp);
   
   while (fgets(buf, 128, sp) != NULL) 
        list[i++]=strdup(buf);
   fclose(sp);
   return 1;
  }

void sortit()
/* [<][>][^][v][top][bottom][index][help] */
  {
   int index=0, count=0;
   char newsgroup[128];

   file_array(rf);
   shell_sort(list, entries); 
   
   unlink(sf);
   sp=fopen(sf, "w"); 

   strcpy(newsgroup, list[0]);
   for(index=0; index<entries; index++)
     {
      if (strcmp(newsgroup, list[index])==0) ++count;
      if (strcmp(newsgroup, list[index])!=0)
        {
         fprintf(sp, "%06d %s", count, newsgroup);
         strcpy(newsgroup, list[index]);
         count=1;
        }
     }
   fprintf(sp, "%06d %s", count, newsgroup);

   fclose(sp);
   free(list);
  
   file_array(sf);
   shell_sort(list, entries);

   unlink(hf);
   sp = fopen(hf, "w");
   for(index=0; index<entries; index++)
    {
     sscanf(list[index], "%d %s", &count, newsgroup);
     if (lowmark<=count) fprintf(sp, "%s\n", newsgroup);
    }
   fclose(sp);
   free(list);
   unlink(rf);
   unlink(sf);
   if (debug>=1) 
     printf("File :- %s sorted and has %d newsgroups\n", hf, entries);
  }

/* [<][>][^][v][top][bottom][index][help] */