mirror of
https://github.com/pragma-/pbot.git
synced 2024-11-29 23:39:24 +01:00
Utils/PriorityQueue: simplify find_enqueue_position with an alias for $self->{queue}
This commit is contained in:
parent
d4f9240c3d
commit
7f3650004e
@ -55,37 +55,40 @@ sub find_enqueue_position {
|
|||||||
|
|
||||||
$priority //= 0;
|
$priority //= 0;
|
||||||
|
|
||||||
|
# shorter alias
|
||||||
|
my $queue = $self->{queue};
|
||||||
|
|
||||||
# no entries in queue yet, early-return first position
|
# no entries in queue yet, early-return first position
|
||||||
return 0 if not @{$self->{queue}};
|
return 0 if not @$queue;
|
||||||
|
|
||||||
# early-return first position if entry's priority is less
|
# early-return first position if entry's priority is less
|
||||||
# than first position's
|
# than first position's
|
||||||
if ($priority < $self->{queue}->[0]->{priority}) {
|
if ($priority < $queue->[0]->{priority}) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
# early-return last position if entry's priority is greater
|
# early-return last position if entry's priority is greater
|
||||||
if ($priority > $self->{queue}->[@{$self->{queue}} - 1]->{priority}) {
|
if ($priority > $queue->[@$queue - 1]->{priority}) {
|
||||||
return scalar @{$self->{queue}};
|
return scalar @$queue;
|
||||||
}
|
}
|
||||||
|
|
||||||
# binary search to find enqueue position
|
# binary search to find enqueue position
|
||||||
|
|
||||||
my $lo = 0;
|
my $lo = 0;
|
||||||
my $hi = scalar @{$self->{queue}} - 1;
|
my $hi = scalar @$queue - 1;
|
||||||
|
|
||||||
while ($lo <= $hi) {
|
while ($lo <= $hi) {
|
||||||
my $mid = int (($hi + $lo) / 2);
|
my $mid = int (($hi + $lo) / 2);
|
||||||
|
|
||||||
if ($priority < $self->{queue}->[$mid]->{priority}) {
|
if ($priority < $queue->[$mid]->{priority}) {
|
||||||
$hi = $mid - 1;
|
$hi = $mid - 1;
|
||||||
} elsif ($priority > $self->{queue}->[$mid]->{priority}) {
|
} elsif ($priority > $queue->[$mid]->{priority}) {
|
||||||
$lo = $mid + 1;
|
$lo = $mid + 1;
|
||||||
} else {
|
} else {
|
||||||
# found a slot with the same priority. we "slide" down the array
|
# found a slot with the same priority. we "slide" down the array
|
||||||
# to append this entry to the end of this region of same-priorities
|
# to append this entry to the end of this region of same-priorities
|
||||||
# and then return the final slot
|
# and then return the final slot
|
||||||
while ($mid < @{$self->{queue}} and $self->{queue}->[$mid]->{priority} == $priority) {
|
while ($mid < @$queue and $queue->[$mid]->{priority} == $priority) {
|
||||||
$mid++;
|
$mid++;
|
||||||
}
|
}
|
||||||
return $mid;
|
return $mid;
|
||||||
|
Loading…
Reference in New Issue
Block a user