您的位置:首页 > 其它

AS3二分查询

2013-09-27 16:37 260 查看
若有一个一定顺序的数组Vector.<Object>, 在 Vector 中以Object的Id顺序的排列.一般最常用的方法是for each循环.但是一但Vector的元素很多的时候,用for each的话,可能会耗掉很多时间.如果,以前学过二分法的同学 , 看到 这篇博文 很可能 会想到 递归,但是 AS3语言递归的话,有很多的毛病 ,你可以 测试 一下 , 递归次数 一长, 它就报错 . 咱得 另辟蹊径...

一个模型 :

package com.ainy.hashmap{
/**
* @author Ainy
* */
public class BoxGiftInfoModel{
private var typeId : uint;
private var name : String;
private var condition : uint;
private var reward : uint;
public function set $typeId ( $value : uint ) : void{
this.typeId = $value;
}
public function set $name ( $value : String ) : void{
this.name = $value;
}
public function set $condition ( $value : uint ) : void{
this.condition = $value;
}
public function set $reward ( $value : uint ) : void{
this.reward = $value;
}
/**类型编号*/
public function get $typeId() : uint{
return this.typeId;
}
/**类型名称*/
public function get $name() : String{
return this.name;
}
/**条件值*/
public function get $condition() : uint{
return this.condition;
}
/**奖励值*/
public function get $reward() : uint{
return this.reward;
}
}
}
二分法:
package com.ainy.hashmap{
public class Section{
public function Section(){
public static function sectionVector($source : Vector.<BoxGiftInfoModel> , $type : uint) : BoxGiftInfoModel{
var $index_mix : uint = 0;                                  //最小的坐标
var $index_max : uint = $source.length - 1;                 //最大的坐标
var $mix : uint = $source[$index_mix].$typeId;              //最小 typeId的值
if($mix == $type){
return $source[0];
}else{
var $max : uint = $source[$index_max].$typeId;          //最大的typeId的值
if($max == $type){
return $source[$index_max];
}else{
while(true){
var $mid : uint = $source[($index_max-$index_mix) / 2].$typeId;             //2分中间值
if($mid == $type){
return $source[($index_max-$index_mix) / 2];
}else if($mid > $type){
$max = $mid;
$index_max = ($index_max-$index_mix) / 2;
if($source[$index_max].$typeId == $type) return $source[$index_max];
}else{
if($index_mix == ($index_max-$index_mix) / 2){
return null;
}else{
$mix = $mid;
$index_mix = ($index_max-$index_mix) / 2;
if($source[$index_mix].$typeId == $type) return $source[$index_mix];
}
}
}
}
}
}
}
}
}
注意 : 我这里Vector.<BoxGiftInfoModel>是按照BoxGiftInfoModel $typeId的升序排列的.这种方案 如是在 Java/C#里面使用的话,建议用 递归 , 写对了 绝不报错 . 在 AS3 中 , 要想使用 二分 提高查询性能的话 , 我想 用这个 比较 好 , 如有 读者 有更好的方案 , 望指教...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  AS3 二分