package
{
/**
* 注意,此类仅仅是为了研究排序算法的效率而作.实际应用时请不要使用.因为AS3的数组本身提供了一个强大的sort函数,它
* 的效率要远远高于本类中的几个函数。
*
* 在冒泡排序、选择排序、插入排序这三个排序算法中冒泡排序的效率是最低的,其次是选择排序,效率最高的是插入排序。下
* 面是一段效率验证测试的代码。
*
* <listing>
* import lib.base.maths.CSortMath;
*
* var list:Array = [];
* for(var i:int = 0; i<1000; i++)
* list.push(Math.random());
*
* var oldTime:Number = getTimer();
* //CSortMath.bubbleSort(list);
* //CSortMath.choiceSort(list);
* //CSortMath.insertSort(list);
* list.sort(Array.NUMERIC);
* trace(getTimer() - oldTime);
*
* //time
* //bubble 202
* //choice 100
* //insert 98
* //Array.sort 1
* <listing> <p>
*
* 明显Array.sort效率要高很多很多。
*
* 作者:Brant.Hu<p>
* 日期:2009<p>
*/
publicclass CSortMath extends Object
{
public static const INCREASE:String = "increase";
public static const DECREASE:String = "decrease";
/**
*
* 冒泡排序算法排序。对一个数字数组进行升序或降序排列
*
* @param list 要排序的数字数组
* @param type 排序类型。用CMath.INCREASE或字符串"increase"指定升序排序,用CMath.DECREASE或"decrease"降序
* @return 排序结果
*
*/
publicstatic function bubbleSort(list:Array, tyep:String = INCREASE):Array
{
var temp:Number;
var i:int;
var j:int;
if(tyep == INCREASE)
{
for(i = 1; i < list.length; i++)
{
for(j = 0; j < list.length - i; j++)
{
if(list[j] > list[j + 1])
{
temp= list[j];
list[j]= list[j + 1];
list[j+ 1] = temp;
}
}
}
}
else
{
for(i = 1; i < list.length; i++)
{
for(j = 0; j < list.length - i; j++)
{
if(list[j] < list[j + 1])
{
temp= list[j];
list[j]= list[j + 1];
list[j+ 1] = temp;
}
}
}
}
return list;
}
/**
*
* 选择排序算法排序。对一个数字数组进行升序或降序排列
*
* @param list 要排序的数字数组
* @param type 排序类型。用CMath.INCREASE或字符串"increase"指定升序排序,用CMath.DECREASE或"decrease"降序
* @return 排序结果
*/
public static function choiceSort(list:Array, type:String = INCREASE):Array
{
var index:int;
var temp:Number;
var i:int;
var j:int;
if(type == INCREASE)
{
for(i = 0; i < list.length - 1; i++)
{
index= i;
for(j = i + 1; j < list.length; j++)
if(list[j] < list[index])
index = j;
temp= list[index];
list[index]= list[i];
list[i]= temp;
}
}
else
{
for(i = 0; i < list.length - 1; i++)
{
index= i;
for(j = i + 1; j < list.length; j++)
if(list[j] > list[index])
index = j;
temp= list[index];
list[index]= list[i];
list[i]= temp;
}
}
return list;
}
/**
* 插入排序算法排序。对一个数字数组进行升序或降序排列
*
* @param list 要排序的数字数组
* @param type 排序类型。用CMath.INCREASE或字符串"increase"指定升序排序,用CMath.DECREASE或"decrease"降序
* @return 排序结果
*/
publicstatic function insertSort(list:Array, type:String = INCREASE):Array
{
var temp:Number;
var i:int;
var j:int;
if(type == INCREASE)
{
for(i = 1; i < list.length; i++)
{
temp= list[i];
for(j = i; (j > 0) && (list[j - 1] > temp); j--)
list[j]= list[j - 1];
list[j]= temp;
}
}
else
{
for(i = 1; i < list.length; i++)
{
temp= list[i];
for(j = i; (j > 0) && (list[j - 1] < temp); j--)
list[j]= list[j - 1];
list[j]= temp;
}
}
return list;
}
}
}
AS排序算法——给准备面试的朋友献点爱心
最新推荐文章于 2022-12-03 11:18:55 发布