Created
January 19, 2013 08:29
-
-
Save lynxerzhang/4571434 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package | |
{ | |
/** | |
* forked from http://jacksondunstan.com/articles/1848 | |
*/ | |
public class SortedArray | |
{ | |
private var _ary:Array = []; | |
private var _start:int = 0; | |
private var _middle:int; | |
private var _right:int; | |
private var _element:*; | |
/** | |
* add the specfied element d into the sortedArray | |
* @param d | |
*/ | |
public function add(d:*):void { | |
_start = 0; | |
_right = _ary.length - 1; | |
while (_start <= _right) { | |
_middle = (_start + _right) * .5; | |
_element = _ary[_middle]; | |
if (_element > d) { | |
_right = _middle - 1; | |
} | |
else if (_element < d) { | |
_start = _middle + 1; | |
} | |
else { | |
//not change the same element's index | |
_ary.splice(_middle + 1, 0, d); | |
return; | |
} | |
} | |
_ary.splice(_start, 0, d); | |
} | |
/** | |
* add multi elements into array | |
* @param ...args | |
*/ | |
public function adds(...args):void { | |
if (_ary.length == 0) { | |
_ary = _ary.concat.apply(_ary, args); | |
_ary = _ary.sort(Array.NUMERIC); | |
} | |
else { | |
var len:int = args.length; | |
while (--len > -1) { | |
if (args[len] is Array) { | |
adds.apply(null, args[len] as Array); | |
} | |
else { | |
add(args[len]); | |
} | |
} | |
} | |
} | |
/** | |
* remove specfied element d | |
* @param d | |
*/ | |
public function remove(d:*):void { | |
var i:int = indexOf(d); | |
if (i != -1) { | |
_ary.splice(i, 1); | |
} | |
} | |
/** | |
* remove multi elements | |
* @param ...args | |
*/ | |
public function removes(...args):void { | |
var len:int = args.length; | |
while (--len > -1) { | |
if (args[len] is Array) { | |
removes.apply(null, args[len] as Array); | |
} | |
else { | |
remove(args[len]); | |
} | |
} | |
} | |
/** | |
* get the raw array object | |
* do not change element use [] operator or push unshift method | |
*/ | |
public function get array():Array { | |
return this._ary; | |
} | |
/** | |
* get the specfied element's index | |
* @param d element | |
* @return | |
*/ | |
public function indexOf(d:*):int { | |
_start = 0; | |
_right = _ary.length - 1; | |
while (_start <= _right) { | |
_middle = (_start + _right) * .5; | |
_element = _ary[_middle]; | |
if (_element > d) { | |
_right = _middle - 1; | |
} | |
else if (_element < d) { | |
_start = _middle + 1; | |
} | |
else { | |
return _middle; | |
} | |
} | |
return -1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment