home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 5 Edit / 05-Edit.zip / me34src.zip / me3 / util / ssort.c < prev    next >
C/C++ Source or Header  |  1995-01-14  |  1KB  |  56 lines

  1. /* ssort.c : a general shell sort
  2.  * Same parameters as qsort(3)
  3.  * Input:
  4.  *   list:  a list of objects to be sorted
  5.  *   items:  number of objects in the list
  6.  *   item_size:  sizeof(object)
  7.  *   cmp:  routine that compares two objects.  Its passed pointers the
  8.  *     objects to be compared.
  9.  *     It returns: <0 if a < b, 0 if a == b, >0 if a > b
  10.  * Output:  a sorted list.
  11.  * C Durland  10/89    Public Domain
  12.  */
  13.  
  14. #define LIST(j) (list +(j)*item_size)
  15.  
  16. #ifdef __STDC__
  17. void ssort(char *list, int items, int item_size, int (*cmp)(char *, char *))
  18. #else
  19. void ssort(list,items,item_size,cmp)
  20.   char *list;
  21.   int items, item_size;
  22.   int (*cmp)();
  23. #endif
  24. {
  25.   char buf[128];    /* !!! Must be at least item_size bytes. Should malloc() */
  26.   register int gap, i, j;
  27.  
  28.   for (gap = items/2; gap; gap /= 2)
  29.     for (i = gap; i < items; i++)
  30.       for (j = i-gap; j >= 0; j -= gap)
  31.       {
  32.     if ((*cmp)(LIST(j),LIST(j+gap)) <= 0) break;
  33.     memcpy(buf,LIST(j),item_size);
  34.     memcpy(LIST(j),LIST(j+gap),item_size);
  35.     memcpy(LIST(j+gap),buf,item_size);
  36.       }
  37. }
  38.  
  39. #ifdef TEST
  40.  
  41. #define N 20
  42. int list[N];
  43.  
  44. int icmp(a,b) int *a,*b; { return *a -*b; }
  45.  
  46. main()
  47. {
  48.   int j;
  49.  
  50.   for (j = 0; j<N; j++) list[j] = rand();
  51.   ssort((char *)list,N,sizeof(int),icmp);
  52.   for (j = 0; j<N; j++) printf("list[%d] = %d\n",j,list[j]);
  53. }
  54.  
  55. #endif
  56.