From eb4b8674af8e2f5fb92c743a79163e29ff7ac3df Mon Sep 17 00:00:00 2001 From: Tom Conkling Date: Sun, 26 Apr 2009 20:34:29 +0000 Subject: [PATCH] ArrayUtil.sortedInsert git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@5746 542714f4-19e9-0310-aa3c-eee0fc999fb1 --- src/as/com/threerings/util/ArrayUtil.as | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/as/com/threerings/util/ArrayUtil.as b/src/as/com/threerings/util/ArrayUtil.as index acafcc23c..ea2c392e7 100644 --- a/src/as/com/threerings/util/ArrayUtil.as +++ b/src/as/com/threerings/util/ArrayUtil.as @@ -92,6 +92,41 @@ public class ArrayUtil } } + /** + * Inserts an object into a sorted Array in its correct, sorted location. + * + * @param comp a function that takes two objects in the array and returns -1 if the first + * object should appear before the second in the container, 1 if it should appear after, + * and 0 if the order does not matter. If omitted, Comparators.COMPARABLE is used and + * the array elements should be Comparable objects. + * + * @return the index of the inserted item + */ + public static function sortedInsert (arr :Array, val :*, comp :Function = null) :int + { + if (comp == null) { + comp = Comparators.COMPARABLE; + } + + var insertedIdx :int = -1; + var nn :int = arr.length; + for (var ii :int = 0; ii < nn; ii++) { + var compVal :* = arr[ii]; + if (comp(val, compVal) <= 0) { + arr.splice(ii, 0, val); + insertedIdx = ii; + break; + } + } + + if (insertedIdx < 0) { + arr.push(val); + insertedIdx = arr.length - 1; + } + + return insertedIdx; + } + /** * Randomly shuffle the elements in the specified array. *