Re: qsort from "George" at Sep 16, 98 11:11:24 pm

From: Andrew Helm (ashe@IGLOU.COM)
Date: 09/16/98


On Wed, 16 Sep 1998, George wrote;
>
>Been fiddling with qsort() and trying to figure out why it gives me an
>index value of 14,000+ occasionally when running.  Basically the spell
>sorting didn't work after I tested it further than initially.
>
>Anyway, in http://www.circlemud.org/~greerga/comp.c you'll find a copy of
>the program with settings for your native qsort() or _quicksort() (the gnu
>libc 2 version).  Basically wondering if I'm doing something wrong or if
>I'm just crazy. :)

The two values that comp() compares are not index values for the array
qsort is sorting but are the values of actual elements. That means

        strcmp(spells[spell_sort_info[a]], spells[spell_sort_info[b]]);

should be

        strcmp(spells[a], spells[b]);

Also, the number of elements count you were passing qsort was incorrect
because reserved isn't being sorted.


Here's some working code. (I assume you don't care about sorting values
which start with a '!')

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

const char *spells[] = {
        [big list snipped]
};

int spell_sort_info[MAX_SKILLS];

int comp(const void *x, const void *y) {
  int a = *(int *)x;
  int b = *(int *)y;

  if (*spells[a] == '!')
    return (*spells[b] != '!');

  if (*spells[b] == '!')
    return -1;

  return (strcmp(spells[a], spells[b]));
}

int main() {
  int i;

  for (i = 0; i < MAX_SKILLS; ++i)
    spell_sort_info[i] = i + 1;

  qsort(spell_sort_info, MAX_SKILLS, sizeof(int), comp);

  printf("\n\nOrder:\n");
  for (i = 0; i < MAX_SKILLS; ++i)
    printf("#%3d: %s\n", i, spells[spell_sort_info[i]]);

  return EXIT_SUCCESS;
}


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     | http://democracy.queensu.ca/~fletcher/Circle/list-faq.html |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/15/00 PST