From 4c94d8635e08b42f5bb3c8558d319d4a32c1b5f0 Mon Sep 17 00:00:00 2001 From: Britt Cyr Date: Thu, 29 Aug 2024 07:03:47 -0400 Subject: [PATCH] flip the sort order for red black tree iter (#41) --- lib/src/red_black_tree.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/lib/src/red_black_tree.rs b/lib/src/red_black_tree.rs index 278c52252..6d2eca879 100644 --- a/lib/src/red_black_tree.rs +++ b/lib/src/red_black_tree.rs @@ -54,11 +54,15 @@ impl<'a, V: TreeValue> RedBlackTreeReadOnly<'a, V> { } } - /// Sorted iterator starting from the min. + /// Sorted iterator starting from the max. pub fn iter(&self) -> RedBlackTreeReadOnlyIterator { RedBlackTreeReadOnlyIterator { tree: self, - index: self.get_min_index::(), + index: if self.max_index == NIL { + self.get_max_index() + } else { + self.max_index + }, } } } @@ -964,12 +968,15 @@ impl<'a, V: TreeValue> RedBlackTree<'a, V> { } } - // TODO: Go from max to min because that would be cheaper as we already store max - /// Sorted iterator starting from the min. + /// Sorted iterator starting from the max. pub fn iter(&self) -> RedBlackTreeIterator { RedBlackTreeIterator { tree: self, - index: self.get_min_index::(), + index: if self.max_index == NIL { + self.get_max_index() + } else { + self.max_index + }, } } @@ -1098,12 +1105,12 @@ impl<'a, V: TreeValue> Iterator for RedBlackTreeIterator<'a, V> { fn next(&mut self) -> Option { let index: DataIndex = self.index; - let successor_index: DataIndex = self.tree.get_successor_index::(self.index); + let predecessor_index: DataIndex = self.tree.get_predecessor_index::(self.index); if index == NIL { None } else { let result: &RBNode = get_helper::>(self.tree.data, index); - self.index = successor_index; + self.index = predecessor_index; Some((index, result)) } } @@ -1119,12 +1126,12 @@ impl<'a, V: TreeValue> Iterator for RedBlackTreeReadOnlyIterator<'a, V> { fn next(&mut self) -> Option { let index: DataIndex = self.index; - let successor_index: DataIndex = self.tree.get_successor_index::(self.index); + let predecessor_index: DataIndex = self.tree.get_predecessor_index::(self.index); if index == NIL { None } else { let result: &RBNode = get_helper::>(self.tree.data, index); - self.index = successor_index; + self.index = predecessor_index; Some((index, result)) } }