Skip to content

Commit cffe349

Browse files
committed
[array/bubblesortItem] fix edge case
1 parent af62638 commit cffe349

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

array.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,13 +205,13 @@ export const bubblesortItem = (arr, i, compareFn) => {
205205
const n = arr[i]
206206
let j = i
207207
// try to sort to the right
208-
while (compareFn(n, arr[j + 1]) > 0) {
208+
while (j + 1 < arr.length && compareFn(n, arr[j + 1]) > 0) {
209209
arr[j] = arr[j + 1]
210210
arr[++j] = n
211211
}
212212
if (i === j && j > 0) { // no change yet
213213
// sort to the left
214-
while (compareFn(arr[j - 1], n) > 0) {
214+
while (j > 0 && compareFn(arr[j - 1], n) > 0) {
215215
arr[j] = arr[j - 1]
216216
arr[--j] = n
217217
}

array.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,16 @@ export const testUnique = _tc => {
119119
t.compare([], array.uniqueBy([], o => o))
120120
}
121121

122+
/**
123+
* @param {t.TestCase} tc
124+
*/
125+
export const testBubblesortItemEdgeCases = tc => {
126+
// does not throw..
127+
array.bubblesortItem([1], 0, (a, b) => a - b)
128+
array.bubblesortItem([2, 1], 1, (a, b) => a - b)
129+
array.bubblesortItem([2, 1], 0, (a, b) => a - b)
130+
}
131+
122132
/**
123133
* @param {t.TestCase} tc
124134
*/

0 commit comments

Comments
 (0)