summaryrefslogtreecommitdiff
path: root/lib/fstree/fstree_sort.c
blob: cd012352bbf8c31a7d9897573907c1a2db68fe7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* SPDX-License-Identifier: GPL-3.0-or-later */
#include "fstree.h"

#include <string.h>

static tree_node_t *merge(tree_node_t *lhs, tree_node_t *rhs)
{
	tree_node_t *head = NULL, *prev = NULL, *it;

	while (lhs != NULL && rhs != NULL) {
		if (strcmp(lhs->name, rhs->name) <= 0) {
			it = lhs;
			lhs = lhs->next;
		} else {
			it = rhs;
			rhs = rhs->next;
		}

		it->next = NULL;

		if (prev != NULL) {
			prev->next = it;
			prev = it;
		} else {
			prev = head = it;
		}
	}

	it = (lhs != NULL ? lhs : rhs);

	if (prev != NULL) {
		prev->next = it;
	} else {
		head = it;
	}

	return head;
}

tree_node_t *tree_node_list_sort(tree_node_t *head)
{
	tree_node_t *it, *prev;
	size_t i, count = 0;

	for (it = head; it != NULL; it = it->next)
		++count;

	if (count < 2)
		return head;

	prev = NULL;
	it = head;

	for (i = 0; i < count / 2; ++i) {
		prev = it;
		it = it->next;
	}

	prev->next = NULL;

	return merge(tree_node_list_sort(head), tree_node_list_sort(it));
}

void tree_node_sort_recursive(tree_node_t *n)
{
	n->data.dir->children = tree_node_list_sort(n->data.dir->children);

	for (n = n->data.dir->children; n != NULL; n = n->next) {
		if (S_ISDIR(n->mode))
			tree_node_sort_recursive(n);
	}
}