Re: [gtk-list] Re: glib: how to sort a doubly linked list?



Here is my contribution to list sorting.  This is a piece of XQF
source code (http://www.botik.ru/~roma/quake).


#include <stdlib.h>	/* qsort() */

GList *qsort_list (GList *list, int (*func) (const void *, const void *)) {
  gpointer *array;
  gpointer *ptr;
  GList *tmp;
  int len;

  len = g_list_length (list);

  switch (len) {

  case 0:
  case 1:
    break;

  case 2:
    if (func (&list->data, &list->next->data) > 0) {
      tmp = list->data;
      list->data = list->next->data;
      list->next->data = tmp;
    }
    break;

  default:
    ptr = array = g_malloc (sizeof (gpointer) * len);
    for (tmp = list; tmp; tmp = tmp->next)
      *ptr++ = tmp->data;
    
    qsort (array, len, sizeof (gpointer), func);

    ptr = array;
    for (tmp = list; tmp; tmp = tmp->next)
      tmp->data = *ptr++;
    
    g_free (array);
    break;
  }

  return list;
}


-- 
Roman Pozlevich              e-mail: roma@botik.ru
http://www.botik.ru/~roma    phone: +7 (08535) 98044, fax: +7 (08535) 98278



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]