Eva’s Blog

js–2維數據排序

Posted on: 二月 20, 2009

昨天去tecent面試,突然問我一個2維數組排序的問題,唉,當時竟然沒有達上來!后來想想還是基本功不到位啊!在這里copy網上一個解決方案!

var   temp   =   [
{   x:X-1,   y:Y-1,   ct:5,   d:0},
{   x:X,       y:Y-1,   ct:2,   d:1},
{   x:X+1,   y:Y-1,   ct:7,   d:2},
{   x:X+1,   y:Y,       ct:3,   d:3},
{   x:X+1,   y:Y+1,   ct:0,   d:4},
{   x:X,       y:Y+1,   ct:1,   d:5},
{   x:X-1,   y:Y+1,   ct:6,   d:6},
{   x:X-1,   y:Y,       ct:4,   d:7}
];

做ct的排序。

<script type=”text/javascript”>
function compareIntegers(vNum1,vNum2)
{
if(vNum1>vNum2)
{
return 1;
}
else if(vNum1<vNum2)
{
return -1;
}
else
{
return 0;
}
}
###這個方法可以簡化成

function   cmp(a,b,c)   {
if(a[c]   ==   b[c])
return   0;
return   a[c]   >   b[c]   ?   1:-1;
}  #####

function mySort(arr)
{
arr.sort(compareIntegers);
return arr;
}

string数组排序可以直接用 String的localCompare()方法
function compareStrings(string1,string2)
{
return string1.localeCompare(string2);
}

csdn:

<script>
function   cmp(a,b,c)   {
if(a[c]   ==   b[c])
return   0;
return   a[c]   >   b[c]   ?   1:-1;
}

for(i=0;i<temp.length-1;i++)
for(j=i;j<temp.length;j++)
if(cmp(temp[i],temp[j],”ct”)   >   0)   {
c   =   temp[i]
temp[i]   =   temp[j]
temp[j]   =   c
}
</script>

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

2009年二月
« 1月    
 1
2345678
9101112131415
16171819202122
232425262728  

UED Front_end

Blog Stats

  • 146 hits
%d 博主赞过: