Divine Blood
You are not logged in.


Source Code: http://www.divineblood.org/snippets/list_sort.c

Last Modified: Fri May 21, 2004 6:50pm
Download without markup
Download as zipfile


/*
  list_sort.c
  sort a linked list via qsort
  It just creates an array, fills it with the linked list, qsorts,
  then puts that array back in a list.

  Palrich,
  Divine Blood
  http://www.divineblood.org/
*/

/* merc.h */
#define NEXTPTR(list) ((char *)&(list->next) - (char *)list)
void *list_sort(void *list, int nextpos, int(*compar)(const void *,
  const void *));

/* some .c file */
void *list_sort(void *list, int nextpos, int(*compar)(const void *,
  const void *))
{
  int count = 0, i = 0;
  unsigned char *ptr = list;
  unsigned char **array;
  for (; ptr != NULL; count++)
    ptr = (void *)*(long *)(ptr+nextpos);
  array = malloc(sizeof(void *)*count);
  ptr = list;
  for (; ptr != NULL; ptr = (void *)*(long *)(ptr+nextpos))
    array[i++] = ptr;
  qsort(array, count, sizeof(unsigned char *), compar);
  list = NULL;
  for (count--;count >= 0; count--)
  {
    (void *)*(long *)(array[count]+nextpos) = list;
    list = array[count];
  }
  free(array);
  return list;
}

/* to use it */
list = list_sort(list, NEXTPTR(list), comparison_function);

© 2005 Divine Blood Staff -- Web page by Palrich (palrichatgmail.com)