Skip to content

Commit d22d9fb

Browse files
author
lewis617
committed
Fux bug of sort() function in cookie assign
1 parent c5c5a05 commit d22d9fb

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

ArrayList/ArrayList.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,9 @@ function ArrayList() {
188188

189189
this.findContentChildren = function (cookies) {
190190
this.quickSort();
191-
cookies.sort();
191+
cookies.sort(function (a, b) {
192+
return a - b;
193+
});
192194
var i = 0; // 满足的孩子数量
193195
for (var j = 0; i < array.length && j < cookies.length; j++) { // 遍历饼干
194196
if (array[i] <= cookies[j]) {

ArrayList/ArrayList.test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,13 @@ test('ArrayList', function () {
7373
array = createNonSortedArray();
7474
expect(array.findContentChildren([1, 1])).toBe(1);
7575
expect(array.findContentChildren([1, 2, 3])).toBe(3);
76+
77+
// test for sort() function, eg: 10 and 9, sort will return a wrong answer.
78+
array = new ArrayList();
79+
array.insert(10);
80+
array.insert(9);
81+
array.insert(8);
82+
array.insert(7);
83+
array.insert(6);
84+
expect(array.findContentChildren([7, 6, 5])).toBe(2);
7685
});

0 commit comments

Comments
 (0)