var arr = [1,2,3,5,2,5,3,6,2,6,2,6,2,5,9,6,8,54,3,6,8];
arrsort(function(a,b){return a-b});
这样是升序排列。
如果希望降序排列,就写成return b-a;<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script> var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
99, 100];
for(var i=0;i<arrlength;i++){
documentwrite(arr[i]+",")
}
</script>
</head>
<body>
</body>
</html>var arr=[12,9,2,31,11,23,17];
var arr1=new array();//奇数
var arr2=new array();//偶数
for(var i=0;i<arrlength;i++)
{
if(arr[i]%2==1)
{
arr1add(arr[i]);
}
else
{arr2add(arr[i]);}
}
arr1sort(function(a,b){
return a-b});
arr2sort(function(a,b){
return b-a});
arr=arr1concat(arr2);数组排序,你可以直接调用javascript原生自带的sort()方法,比如下面的例子:
// Arrayprototypesort() //原生自带的数组的排序方法;
var fruit = ['apples', 'bananas', 'Cherries']; //定义一个数组
fruitsort(); // ['Cherries', 'apples', 'bananas']; //按字母排序的结果
var scores = [1, 2, 10, 21]; //定义一个数字排序,你发现其实还是按照字母序排列的
scoressort(); // [1, 10, 2, 21]
如果希望按照期望的数字排序。
scoressort(function(a,b){return a-b}); //这样的就可以了。结果为:21 10 2 1
var things = ['word', 'Word', '1 Word', '2 Words'];
thingssort(); // ['1 Word', '2 Words', 'Word', 'word']
// In Unicode, numbers come before upper case letters,
// which come before lower case letters
不要JS自己的方法?
下面是一个快速排序算法的JS实现:
var arr = [1,4,2,5,7];function QuickSort(arr){
if (arrlength <= 1){
return arr;
} else if (arrlength === 2) {
if (arr[0] <= arr[1]) return arr;
else return [arr[1], arr[0]];
} else {
var rndIndex = (Mathrandom() arrlength) | 0;
var mid = arr[rndIndex];
arrsplice(rndIndex, 1);
var left = [], right = [];
for (var i=arrlength-1; i>-1; i--) {
if (arr[i] <= mid) leftpush(arr[i]);
else rightpush(arr[i]);
}
return QuickSort(left)concat(mid, QuickSort(right));
}
}
alert(QuickSort(arr));
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)