数据交换
a=2,b=3,如何实现交换,结果为a=3,b=2.
用二进制
a= a^b //01
b= a^b //10 2
a= a^b //11 3
另一种方法:
a = a+b
b = a-b
a = a-b
如何对数组[10,30,20,15,40]进行排序,要从大到小
1.
_init:function(){
var a = [10,30,20,15,40];
var b =[10];
for(var i = 1;i<a.length,i++){
for(car j = 0;j<a.length-1;i++){
if(a[i] >= b[j] || j == b.length){
b.splice(j,0,a[i]); //在数组j和a[i]之间插入元素,0代表位置
break;
}
}
}
cc.log(b)
}
2.
var a = [10,30,20,15,40];
for(var i = 1;i<a.length,i++){
for(car j = i+1;j<a.length;i++){
cc.log(i,a[i],j,a[j]);
if(a[j] > b[i]){
var temp = a[j];
a[i] = a[j];
a[j] = temp;
}
cc.log("end",i.a[i],j,a[j]);
}
}
cc.log(a.toString());
3.
_init:function(){
function sortNumber(a,b){
return a-b;
}
var a = [10,30,20,15,40];
cc.log(a.sort(sortNumber));
}从小排到大
若return b-a
则结果为从大排到小