#<- sort

record = 
{
  int x; char name[MAX_NAME];    
};

MAX_* // NAME : 1024,
         RECORDS : 5;

void >> ()
{
  print_array ();
  print_list ();
}

void print_array ()
{
  p_record records[MAX_RECORDS] = {};

  record r_1 = { x : 1, name : "#1" }; records[0] = &r_1;
  record r_2 = { x : 5, name : "#5" }; records[1] = &r_2;
  record r_3 = { x : 9, name : "#9" }; records[2] = &r_3;
  record r_4 = { x : 7, name : "#7" }; records[3] = &r_4;
  record r_5 = { x : 3, name : "#3" }; records[4] = &r_5;

  length = array_length (records);

  sort (records, length, (p_record first, p_record second) {
                                                             return (first->x < second->x) ? 1 : 0;
                                                           });

  for (i = 0; i < length; i ++)
  {
    print ("%s" "\n", records[i].s);
  }
}

void print_list ()
{
  record r_1 = { x : 1, name : "#1" };
  record r_2 = { x : 5, name : "#5" };
  record r_3 = { x : 9, name : "#9" };
  record r_4 = { x : 7, name : "#7" };
  record r_5 = { x : 3, name : "#3" };

  vb records = alloc (T_LIST, T_LINK, rs), 
  {
    rs[] = { 
             alloc (T_POINTER | T_STRUCT, record, AC_ANY_POINTERS, &r_1), 
             alloc (T_POINTER | T_STRUCT, record, AC_ANY_POINTERS, &r_2), 
             alloc (T_POINTER | T_STRUCT, record, AC_ANY_POINTERS, &r_3), 
             alloc (T_POINTER | T_STRUCT, record, AC_ANY_POINTERS, &r_4), 
             alloc (T_POINTER | T_STRUCT, record, AC_ANY_POINTERS, &r_5)
           }
  };

  vb sorted = alloc (T_LIST, T_LINK);

  sort (sorted, records, (vb first, vb current) {
                                                  p_record first' = get_pointer (first, record);
                                                  p_record current' = get_pointer (current, record);

                                                  return (current'->x < first'->x) ? 1 : 0;
                                                }); 

  vb current = alloc (T_LINK);

  for (i = 0; i < length; i ++)
  {
    detach (current, sorted, REDUCE_LIST), { reset_link (current) };

    print ("%s" "\n", current'->name), { current' = get_pointer (current, record) };
  },
  {
    length = _ (sorted)
  }
}
/
{
  free (&current, &sorted);
  free (&records, VM_FREE_ALL);
}