Tizen Native API  5.5
Sorting Eina_List elements

If you don't know how to create lists see Adding elements to Eina_List.

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

int
main(int argc, char **argv)
{
   (void)argc;
   (void)argv;
   Eina_List *list = NULL, *other_list = NULL;
   Eina_List *l;
   void *data;
   int cmp_result;
   Eina_Compare_Cb cmp_func = (Eina_Compare_Cb)strcmp;

   eina_init();

   list = eina_list_append(list, "starbuck");
   list = eina_list_append(list, "appolo");
   list = eina_list_append(list, "boomer");
This is the code we have already seen to create a list. Now if we need to search the list we can do it like this:
   data = eina_list_search_unsorted(list, cmp_func, "boomer");
   l = eina_list_search_unsorted_list(list, cmp_func, "boomer");
   if (l->data != data)
     return 1;

However if searching the list multiple times it probably is better to sort the list since the sorted_search functions are much faster:

   list = eina_list_sort(list, 0, cmp_func);

   data = eina_list_search_sorted(list, cmp_func, "starbuck");
   l = eina_list_search_sorted_list(list, cmp_func, "starbuck");
   if (l->data != data)
     return 1;

Once the list is sorted it's not a good idea to use append/prepend functions since that would add the element in the wrong place, instead elements should be added with eina_list_sorted_insert():

   list = eina_list_sorted_insert(list, cmp_func, "helo");

A noteworthy use case is adding an element to a list only if it doesn't exist already, this can accomplished by searching for the element that is closest to what is being added, and if that doesn't match add:

   l = eina_list_search_sorted_near_list(list, cmp_func, "hera", &cmp_result);
   if (cmp_result > 0)
     list = eina_list_prepend_relative_list(list, "hera", l);
   else if (cmp_result < 0)
     list = eina_list_append_relative_list(list, "hera", l);

Note:
eina_list_search_sorted_near_list() will tell you not only the nearest node to what was searched for but how it compares to your term, this way it is easy to know if you have to add before or after that node.

It is sometimes useful to get a portion of the list as another list, here we take every element that comes after "boomer" and split it into "other_list":

   l = eina_list_search_sorted_list(list, cmp_func, "boomer");
   list = eina_list_split_list(list, l, &other_list);

It is also possible to add entire lists of elements using eina_list_sorted_merge():

   other_list = eina_list_sort(other_list, 0, cmp_func);

   list = eina_list_sorted_merge(list, other_list, cmp_func);

And as always release memory and shutdown eina before ending:

   eina_list_free(list);

   eina_shutdown();

   return 0;
}

The full source code can be found on the examples folder on the eina_list_02.c file.