Answer the question
In order to leave comments, you need to log in
How to sort an array with elements depending on each other?
View array
[
[
"name1" => ["value" => "v", "depends" => ["name3, name 5"]
],
[
"name2" => ["value" => "v", "depends" => ["name1"]
],
[
"name3" => ["value" => "v", "depends" => ["name5"]
],
[
"name4" => ["value" => "v", "depends" => ["name1, name 2"]
],
[
"name5" => ["value" => "v", "depends" => []
],
]
[
[
"name5" => ["value" => "v", "depends" => []
],
[
"name3" => ["value" => "v", "depends" => ["name5"]
],
[
"name1" => ["value" => "v", "depends" => ["name3, name 5"]
],
[
"name2" => ["value" => "v", "depends" => ["name1"]
],
[
"name4" => ["value" => "v", "depends" => ["name1, name 2"]
],
]
Answer the question
In order to leave comments, you need to log in
This is the so-called "topological sort". It is done through sequential depth-first search, starting with all possible elements.
алг recurse(поссылке x : элемент, поссылке результат : список)
если x.метка = чёрный
возврат
если x.метка = серый
стоп ("найдена циклическая зависимость")
x.метка := серый
для всех y : зависимых от x
recurse(y)
x.метка := чёрный
результат.добавить(x)
алг main()
для всех x : массив
x.метка := белый
result := []
для всех x : массив
recurse(x, result)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question