用javascript模仿java实现的有序链表,实现按对象的某个属性对对象进行排序。
<script>
/**
* 按对象中指定的属性名升序排序(如需指定升序或降序还需改进)
* @param objs,对象数组
* @param attrName 要排序的属性名
* @return 返回排序后的对象数组
*/
function sortObjArray(objs,attrName){
if(arguments.length<2||attrName==null||attrName==""){
alert("请指定要排序的属性名");return objs;
}
if(!objs.length||objs.length<2)return objs;
var tempObjs=[];
//将数组放到链表中
for(var i=0;i<objs.length;i++){
tempObjs[i]=new Link1();
tempObjs[i].obj=objs[i];
}
//排序
var slist=new SortedList();
slist.SortedList(tempObjs,attrName);
var returnArray=new Array();
for(var i=0;i<objs.length;i++){
returnArray[i]=slist.remove().obj;
}
return returnArray;
}
function Link1(){}
Link1.prototype.obj=null;
Link1.prototype.next1=new Link1();
Link1.prototype.Link1=function(object){
obj=object;
}
function SortedList(){}
SortedList.prototype.first=new Link1();
SortedList.prototype.SortedList=function(linkArr,nm){
var sortedList=new SortedList();
sortedList.first=null;
for(j=0;j<linkArr.length;j++){
sortedList.insert(linkArr[j],nm);
}
}
var SortedVar=new SortedList();
SortedList.prototype.insert=function(lnk,nm){
var previous1=null;
var current1=SortedVar.first;
while(current1.obj!=null&&lnk.obj[nm]>current1.obj[nm]){
previous1=current1;
current1=current1.next1;
}
if(previous1==null){
SortedVar.first=lnk;
}else{
privious1=new Link1();
previous1.next1=lnk;
}
lnk.next1=current1;
}
SortedList.prototype.remove=function (){
var temp=new Link1();
temp=SortedVar.first;
SortedVar.first=SortedVar.first.next1;
return temp;
}
</script>