js二维数组排序的简单示例代码
人气:0如下所示:
复制代码 代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<script type="text/javascript">
<!--
function getCard(m){
var ret = [], rnd;
for(var i = 0; i < m; i++){
rnd = Math.floor(Math.random()*(i+0.9999));
ret[i] = ret[rnd];
ret[rnd] = i
}
return ret;
}
var data = [];
{
for(var i = 0; i < 100; i ++){
data.push(getCard(10));
}
}
// 二维数据排序
function mySort(array, col, ord, b, e){
if(array.length == 0) return;
/https://img.qb5200.com/download-x/document.write("排序前"+array);
var t = [], s, i, curCol = col[0];
for(i = b; i < e; i ++){
s = new String(array[i][curCol]);
s._obj = array[i];
t.push(s)
}
t.sort();
if(ord[0] == "des"){
t.reverse();
}
for(i = 0; i < e - b; i++){
/https://img.qb5200.com/download-x/document.write("<br/>");
/https://img.qb5200.com/download-x/document.write(array[i]);
/https://img.qb5200.com/download-x/document.write("<br/>");
/https://img.qb5200.com/download-x/document.write(t[i]._obj);
/https://img.qb5200.com/download-x/document.write("<br/>");
/https://img.qb5200.com/download-x/document.write(t[i]._obj == array[b+i]);
array[b+i] = t[i]._obj;
}
/https://img.qb5200.com/download-x/document.write("排序后====================<br/>")
//print(array);
var begin, end;
if(col.length > 1){
col.shift();
ord.shift();
begin = b;
for(i = b; i < e - b - 1; i++){
if( array[i][curCol] != array[i+1][curCol] ){
end = i+1;
/https://img.qb5200.com/download-x/document.write("begin="+begin+"end="+end+"<br/>");
mySort(array,col,ord,begin,end);
begin = end;
}
}
if(begin != e){
mySort(array,col,ord,begin,e);
}
}
/https://img.qb5200.com/download-x/document.write("<br/>");
/https://img.qb5200.com/download-x/document.write("排序后"+array);
}
function print(data){
for(var i = 0; i < data.length; i++){
document.write(data[i]+"<br/>");
}
}
document.write("排序前====================<br/>");
print(data);
var b = new Date().getTime();;
mySort(data, [0,1,2],['asc','des','asc'],0,data.length);
document.write("用时"+(new Date().getTime() - b));
document.write("排序后====================<br/>")
print(data);
//-->
</script>
</head>
<body>
</body>
</html>
加载全部内容