From 8f744862644ed14a48d414bc12725c3c1495dba1 Mon Sep 17 00:00:00 2001 From: Yohan Simard Date: Thu, 2 Apr 2020 23:20:33 +0200 Subject: [PATCH] Get rid of array.indexOf(x) in the remove() function --- .../insa/graphs/algorithm/utils/BinaryHeap.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/be-graphes-algos/src/main/java/org/insa/graphs/algorithm/utils/BinaryHeap.java b/be-graphes-algos/src/main/java/org/insa/graphs/algorithm/utils/BinaryHeap.java index 6316ea5..b96d49b 100644 --- a/be-graphes-algos/src/main/java/org/insa/graphs/algorithm/utils/BinaryHeap.java +++ b/be-graphes-algos/src/main/java/org/insa/graphs/algorithm/utils/BinaryHeap.java @@ -137,8 +137,18 @@ public class BinaryHeap> implements PriorityQueue { @Override public void remove(E x) throws ElementNotFoundException { - int index = array.indexOf(x); - if (index == -1 || index >= currentSize) throw new ElementNotFoundException(x); + int index = 0; + // We avoid array.indexOf(x) because we don't need to search + // through the whole list, we can stop at indexSize. + boolean found = false; + while(!found && index < currentSize) { + if (array.get(index) == x) + found =true; + else + index++; + } + + if (!found) throw new ElementNotFoundException(x); arraySet(index, array.get(--currentSize)); percolateUp(index); percolateDown(index);