您是否必须使用比较函数对数组进行排序? [英] Do you have to use a compare function to sort an array of numbers?

查看:108
本文介绍了您是否必须使用比较函数对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是,为了对一系列数字进行排序,您必须执行以下操作:

I was under the impression that in order to sort an array of numbers you had to do the following:

var numbers = [4, 1, 2, 3];

function compare(a, b) {
    return a - b;
} 

numbers.sort(compare);

但是,我发现以下似乎有效:

However, I found that the following seems to work:

var numbers = [5, 3, 2, 6, 4, 7];
var sortNumbers = numbers.sort();
console.log(sortNumbers); 

这样做有什么不妥吗?它似乎适用于所有情况。

Is there anything wrong with doing it this way? It seems to work in all cases for me.

推荐答案


它似乎适用于所有情况我。

It seems to work in all cases for me.

您没有考虑任何由字符串表示形式的多个数字组成的数字。
字典默认比较也因负数而失败。

You have not considered any cases of numbers that consist of multiple digits in string representation. The lexicographic default comparison also fails on negative numbers.

参见如何正确排序整数数组以获取更多信息和一些反例。

See How to sort an array of integers correctly for more information and some counterexamples.

这篇关于您是否必须使用比较函数对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆