首页 > 其他分享 >终于明白了 Array.sort(comparator) 的原理

终于明白了 Array.sort(comparator) 的原理

时间:2024-05-10 22:54:41浏览次数:22  
标签:sort function right comparator number Array array

终于明白了 Array.sort(comparator) 的原理

原文地址:
https://www.jameskerr.blog/posts/javascript-sort-comparators/

After 13 years of JavaScript, I finally have a way to remember how the comparator function in Array.sort() works.

使用 JavaScript 13 年之后,我终于有办法记住 Array.sort() 中的比较器函数是如何工作的。

I think the trouble is that all the examples use this shorthand syntax.

我认为问题在于所有示例都使用这种缩写语法。

array.sort((a, b) => a - b); // too hard for me

This is beyond confusing for me.

这让我很困惑。

In the past, I would just try b - a then try a - b and pick which one gave me the result I wanted.

在过去,我只是尝试 b - a 然后尝试 a - b,之后 选择一个给了我我想要的结果的那种写法。

But now I have a mental model simple enough for me to remember.

但现在我有了一个简单易记的心理模型。

First, the sole purpose of the comparator function is to answer this quesions:

首先,比较器函数的唯一目的是回答这个问题:

Where should “a” be placed in the new sorted array? To the left of “b” or to the right?

“a”应该放在新排序数组中的什么位置? 在“b”的左边还是右边?

The arguments passed to the comparator function are usually named a and b.
传递给比较器函数的参数通常命名为a和b。

This makes sense to me, since the first arg comes before the second arg, and a comes before b in the English alphabet.

这对我来说很有意义,因为第一个参数位于第二个参数之前,并且在英语字母表中a位于b之前

These arguments represent two items in the array.

这些参数代表数组中的两个项目。

Now let’s think about the return value.

现在让我们考虑一下返回值。

The function must return a number.

该函数必须返回一个数字。

Numbers exist on a number line going from left to right just like the items in an array.

数字存在于从左到右的数轴上,就像数组中的item项一样。

The negative numbers are on the left, zero is in the middle, and the positive numbers on the right.

负数在左边,零在中间,正数在右边。

-3   -2   -1   0   1   2   3
----------------------------
    a good ol' number line

So check it out, if your comparator function returns a negative number, the first argument a will come first, before b.

所以检查一下,如果你的比较器函数返回一个负数,第一个参数a将出现在b之前。

Just like negative numbers on the number line come first!

就像数轴上的负数先出现一样!

If the function returns a positive number, the first argument a will come after b.
如果函数返回正数,则第一个参数a将在b后面。

The a item will be on the “right” side of of b, just like the positive numbers are on the “right” side of the number
line!

该a项目将位于b 的“右侧” ,就像正数位于数轴的“右侧”一样!

If the function returns 0, there will be no change to the existing order of the elements.

如果函数返回 0,则元素的现有顺序不会改变。

This one was pretty easy to remember.

这个很容易记住。

To summarize, we just want to find out where a goes. Does it go to the left or right of b.

总而言之,我们只是想弄清楚a是要放在b的左边还是右边。

Negative means left, positive means right.

负数表示左,正数表示右。

Number line. Left to right.

数轴上 从左到右。

The “left-to-right-ness” of the number line, the items in an array, the alphabet, and the positional arguments all
finally clicked for me today.

从左到右的数轴、数组中的项、字母表和位置参数 这些,今天,终于让我明白了 array.sort(comparator) 是如何工作的。

Maybe this will click for you too and you can save yourself 13 years of googling “How does array.sort(comparator) work again?”.

也许这也会适合你,你可以节省 13 年的时间去谷歌搜索“ array.sort(comparator) 是如何工作的?”。

标签:sort,function,right,comparator,number,Array,array
From: https://www.cnblogs.com/longmo666/p/18185415

相关文章

  • ArrayList in C#
    https://dotnettutorials.net/lesson/arraylist-collection-csharp/c#中的数组列表是什么?c#中的ArrayList是一个非泛型集合类,它的工作方式类似于数组,但提供了动态调整大小、从集合中间添加和删除元素等功能。c#中的ArrayList可以用来添加未知数据,也就是说,当我们不知道数据的类型......
  • 慎用 Arrays.asList
    Java8提供的Stream流式处理大大减少了集合类各种操作(投影、过滤、转换)的代码量,用起来非常香,所以在实际业务开发中,我们常常会把原始的数组转换为List类数据结构,使得其可以用上Stream流操作。Arrays.asList方法应该是各位最常用的数组一键转换为List的方法了,但这个方法......
  • 【java】ArrayList和LinkedList的区别
    一、ArrayList和LinkedList的相同点ArrayList和LinkedList都是实现了List接口的容器类,用于存储一系列的对象引用,他们都可以对元素的增删改查进行操作。ArrayList、LinkedList、Vector和Stack是List的四个实现类,List是一个接口,它继承与Collection接口,代表有序的队列。其中Vector......
  • 53_Maximum Subarray-最大子数组
    问题描述Givenanintegerarray nums,findthe subarray withthelargestsum,andreturn itssum.给定一个数组nums,找到一个子数组。使它的和最大,返回子数组例子Input:nums=[-2,1,-3,4,-1,2,1,-5,4]Output:6Explanation:子数组[4,-1,2,1]有最大的和6.基......
  • LeetCode 1186. Maximum Subarray Sum with One Deletion
    原题链接在这里:https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/description/题目:Givenanarrayofintegers,returnthemaximumsumfora non-empty subarray(contiguouselements)withatmostoneelementdeletion. Inotherwords,youwa......
  • LeetCode 2210. Count Hills and Valleys in an Array
    原题链接在这里:https://leetcode.com/problems/count-hills-and-valleys-in-an-array/description/题目:Youaregivena 0-indexed integerarray nums.Anindex i ispartofa hill in nums iftheclosestnon-equalneighborsof i aresmallerthan nums[i].......
  • E. Unique Array
    E.UniqueArrayYouaregivenanintegerarray$a$oflength$n$.Asubarrayof$a$isoneofitscontiguoussubsequences(i. e.anarray$[a_l,a_{l+1},\dots,a_r]$forsomeintegers$l$and$r$suchthat$1\lel<r\len$).Let'scallasu......
  • luatable.sort
    localfunctioncompare_with_flag(a,b)--如果a和b都有标志,则按照它们的某个字段进行排序ifa.flagandb.flagthenreturna.sort_field<b.sort_field--假设有一个sort_field字段用于排序--如果a有标志而b没有,则a应该排在b前面elseifa......
  • sort等常用方法和技巧
    sort等常用方法和技巧sortsort(first_pointer,first_pointer+n,cmp)原理:sort并不是简单的快速排序,它对快速排序进行了优化。此外,它还结合了插入排序和堆排序。系统会根据数据形式和数据量自动选择合适的排序方法。它每次排序中不只选择一种方法,比如给一个数据量较大的数组排......
  • Linux脚本——for循环和array数组
    #!/bin/shNodeName=(k8s-master-1k8s-master-2k8s-master-3k8s-node-1k8s-node-2k8s-node-3k8s-node-4k8s-node-5)ipv4=(100.190.110.55100.190.110.56100.190.110.57100.190.110.70100.190.110.71......