Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

list: O(1) sorted insert if we expect append in most cases #318

Merged
merged 1 commit into from
Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion include/re_list.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ void list_insert_before(struct list *list, struct le *le, struct le *ile,
void *data);
void list_insert_after(struct list *list, struct le *le, struct le *ile,
void *data);
void list_insert_sorted(struct list *list, list_sort_h *sh, void *arg,
void list_insert_sorted(struct list *list, list_sort_h *leq, void *arg,
struct le *ile, void *data);
void list_unlink(struct le *le);
void list_sort(struct list *list, list_sort_h *sh, void *arg);
Expand Down
24 changes: 16 additions & 8 deletions src/list/list.c
Original file line number Diff line number Diff line change
Expand Up @@ -210,39 +210,47 @@ void list_insert_after(struct list *list, struct le *le, struct le *ile,
}


static bool le_less(list_sort_h *leq,
struct le *le1, struct le *le2, void *arg)
{
return leq(le1, le2, arg) &&
!(leq(le1, le2, arg) && leq(le2, le1, arg));
}


/**
* Sorted insert into linked list with order defined by the sort handler
*
* @param list Linked list
* @param sh Sort handler
* @param leq Less-equal operator
* @param arg Handler argument
* @param ile List element to insert
* @param data Element data
*/
void list_insert_sorted(struct list *list, list_sort_h *sh, void *arg,
void list_insert_sorted(struct list *list, list_sort_h *leq, void *arg,
struct le *ile, void *data)
{
struct le *le;

if (!list || !sh)
if (!list || !leq)
return;

le = list->head;
le = list->tail;
ile->data = data;

while (le) {

if (sh(le, ile, arg)) {
if (le_less(leq, ile, le, arg)) {

le = le->next;
le = le->prev;
}
else {
list_insert_before(list, le, ile, ile->data);
list_insert_after(list, le, ile, ile->data);
return;
}
}

list_append(list, ile, ile->data);
list_prepend(list, ile, ile->data);
}


Expand Down