javascript Array.sort

javascript Array.sort

起因

再写一个基于浏览器的拆分路线的小程序,需要用到排序算法.不过这个javascript的Array.sort接口和c++的std::sort差的有一些远XP

经过

c++的std::sort需要的比较函数是这样的.

#include <bits/stdc++.h>

using namespace std;

void test_std_sort() {
    
    
	vector<int> v={
    
    2,4,1,3,5};
	//sort(v,[](int x,int y)->bool{return x<y;});
    sort(v.begin(),v.end(),[](int x,int y)->bool{
    
     return x<y;});
	for(auto i:v) cout<<i<<' ';
}

int main() {
    
    
    test_std_sort();
    return 0;
}

或者需要实现一个bool operator<(T x, T y);
std::sort在实现快速排序排序的时候会通过这个符号来判断两个元素是大于小于还是等于(既不大于也不小于).
javascript里是这样

var a=[2,4,1,3,5];
a.sort(function(x,y) {
    
    
	if(x>y)return 1;//the order is wrong change it
	else if(x<y)return -1;//the order is just right no need to change
	else return 0;//no change
});//a.sort((x,y)=>x-y);
console.log(a);

MDN Arrray.sort 这样写到

  • If compareFunction(a, b) returns a value > than 0, sort b before a.
  • If compareFunction(a, b) returns a value ≤ 0, leave a and b in the same order.

结果

不过,因为我只看了这么一点,没有看下面的东西,再加上有点晕,结果就错了.
虽然不知道,javascript 的Array.sort是如何实现的,但是使用以下代码可以看出一些端倪.

var a=[2,3,1,4];
a.sort(function(x,y) {
    
    
	console.log(x,y);
	return x>y?1:-1;//console.assert(x!=y);
});
console.log(a);
/*
3 2
1 3
1 3
1 2
4 2
4 3
(4) [1, 2, 3, 4]
*/

return x>y?1:-1;改为return x>y?1:0,

var a=[2,3,1,4];
a.sort(function(x,y) {
    
    
	console.log(x,y);
	return x>y?1:0;//console.assert(x!=y);
});
console.log(a);
/*
3 2
1 3
4 1
(4) [2, 3, 1, 4]
*/

我猜Array.sort在比较的时候会使用之前两个数字相等的信息.
在其比较函数中必须要分三类,compareFunction(x,y) return { > 0 , x > y < 0 , x < y 0 , x = = y \begin{cases}>0,x>y\\<0,x<y\\0,x==y\end{cases} >0,x>y<0,x<y0,x==y

猜你喜欢

转载自blog.csdn.net/agctXY/article/details/117574691