diff --git a/search/jump_search.ts b/search/jump_search.ts index 45b44e02..e79061d8 100644 --- a/search/jump_search.ts +++ b/search/jump_search.ts @@ -25,13 +25,13 @@ export const jumpSearch = (array: number[], target: number): number => { let currentIdx: number = 0, stepSize: number = Math.floor(Math.sqrt(array.length)), nextIdx: number = stepSize; - + while (array[nextIdx - 1] < target) { currentIdx = nextIdx; nextIdx += stepSize; - if (nextIdx >= array.length) { - nextIdx = array.length - 1; + if (nextIdx > array.length) { + nextIdx = array.length; break; } } diff --git a/search/test/jump_search.test.ts b/search/test/jump_search.test.ts index 59737bdf..3687ccec 100644 --- a/search/test/jump_search.test.ts +++ b/search/test/jump_search.test.ts @@ -5,6 +5,15 @@ describe("Jump search", () => { [[], 1, -1], [[1, 2, 3, 4, 5], 4, 3], [[1, 3, 5, 8, 9], 4, -1], + [[1, 3, 5, 8], 8, 3], + [[1, 3, 5, 8], 9, -1], + [[1, 3, 5, 8], 7, -1], + [[1, 3, 5, 8, 10], 10, 4], + [[1, 3, 5, 8, 10], 11, -1], + [[1, 3, 5, 8, 10], 9, -1], + [[5], 5, 0], + [[5], 100, -1], + [[], 100, -1], ])( "of %o , searching for %o, expected %i", (array: any[], target: any, index: number) => {