Skip to content

Commit aeda385

Browse files
authored
Merge pull request #251 from morganchen12/sorted-array
fix sorting behavior in FUISortedArray
2 parents b6f8ace + 3b64f67 commit aeda385

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

FirebaseDatabaseUI/FUISortedArray.m

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -114,13 +114,16 @@ - (NSInteger)insertSnapshot:(FIRDataSnapshot *)snapshot {
114114
}
115115
}
116116

117+
NSInteger lowerBound = 0;
118+
NSInteger upperBound = self.snapshots.count;
117119
NSInteger index = self.count / 2;
118-
while (index >= 0 && index <= self.count) {
120+
while (index >= 0 && index <= upperBound) {
121+
119122
if (index == 0) {
120-
[self.snapshots insertObject:snapshot atIndex:index];
123+
[self.snapshots insertObject:snapshot atIndex:0];
121124
return 0;
122125
}
123-
if (index == self.count) {
126+
if (index == self.snapshots.count) {
124127
[self.snapshots addObject:snapshot];
125128
return index;
126129
}
@@ -132,11 +135,13 @@ - (NSInteger)insertSnapshot:(FIRDataSnapshot *)snapshot {
132135

133136
if (left == NSOrderedDescending && right == NSOrderedAscending) {
134137
// look left
135-
index /= 2;
138+
upperBound = index;
139+
index = (lowerBound + upperBound) / 2;
136140
continue;
137141
} else if (left == NSOrderedAscending && right == NSOrderedDescending) {
138142
// look right
139-
index = ((self.count - index) / 2) + index + 1;
143+
lowerBound = index + 1;
144+
index = (lowerBound + upperBound) / 2;
140145
continue;
141146
} else if (left == NSOrderedDescending && right == NSOrderedDescending) {
142147
// bad state (array is not sorted to begin with)

0 commit comments

Comments
 (0)