Files
freeCodeCamp/curriculum/challenges/chinese/22-rosetta-code/rosetta-code-challenges/sort-stability.md
2024-01-24 19:52:36 +01:00

3.4 KiB
Raw Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
5a23c84252665b21eecc8014 排序稳定性 1 302308 sort-stability

--description--

When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.

例如,在这个国家和城市表中,对第二 列(城市)的稳定排序将使美国伯明翰高于英国伯明翰。 (尽管在这种情况下,不稳定的排序 可能 将美国伯明翰置于英国伯明翰之上,稳定排序例程将 保证 它)。

UK  London
US  New York
US  Birmingham
UK  Birmingham

类似地仅对第一列进行稳定排序将生成“UK London”作为第一项“US Birmingham”作为最后一项因为具有相同第一个单词的元素的顺序——“UK”或“US”——将保持

--instructions--

编写一个以二维数组为参数的函数。 每个元素有 2 个元素,类似于上面的例子。 该函数应该如前所述对数组进行排序并返回排序后的数组。

--hints--

stableSort 应该是一个函数。

assert(typeof stableSort == 'function');

stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]]) 应该返回一个数组。

assert(
  Array.isArray(
    stableSort([
      ['UK', 'London'],
      ['US', 'New York'],
      ['US', 'Birmingham'],
      ['UK', 'Birmingham']
    ])
  )
);

stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]]) 应该返回 [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]

assert.deepEqual(
  stableSort([
    ['UK', 'London'],
    ['US', 'New York'],
    ['US', 'Birmingham'],
    ['UK', 'Birmingham']
  ]),
  [
    ['US', 'Birmingham'],
    ['UK', 'Birmingham'],
    ['UK', 'London'],
    ['US', 'New York']
  ]
);

stableSort([[2, 2], [1, 2], [1, 4], [1, 5]]) 应该返回 [[2, 2], [1, 2], [1, 4], [1, 5]]

assert.deepEqual(
  stableSort([
    [2, 2],
    [1, 2],
    [1, 4],
    [1, 5]
  ]),
  [
    [2, 2],
    [1, 2],
    [1, 4],
    [1, 5]
  ]
);

stableSort([[11, 55], [12, 45], [11, 45], [32, 45]]) 应该返回 [[12, 45], [11, 45], [32, 45], [11, 55]]

assert.deepEqual(
  stableSort([
    [11, 55],
    [12, 45],
    [11, 45],
    [32, 45]
  ]),
  [
    [12, 45],
    [11, 45],
    [32, 45],
    [11, 55]
  ]
);

stableSort([[10, 22], [1, 2], [1, 4], [1, 5], [10, 9]]) 应该返回 [[1, 2], [1, 4], [1, 5], [10, 9], [10, 22]]

assert.deepEqual(
  stableSort([
    [10, 22],
    [1, 2],
    [1, 4],
    [1, 5],
    [10, 9]
  ]),
  [
    [1, 2],
    [1, 4],
    [1, 5],
    [10, 9],
    [10, 22]
  ]
);

stableSort([[55, 54], [12, 22], [31, 43], [31, 54], [10, 49]]) 应该返回 [[12, 22], [31, 43], [10, 49], [55, 54], [31, 54]]

assert.deepEqual(
  stableSort([
    [55, 54],
    [12, 22],
    [31, 43],
    [31, 54],
    [10, 49]
  ]),
  [
    [12, 22],
    [31, 43],
    [10, 49],
    [55, 54],
    [31, 54]
  ]
);

--seed--

--seed-contents--

function stableSort(arr) {

}

--solutions--

function stableSort(arr) {
  arr.sort(function(a, b) {
    return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0;
  });
  return arr;
}