diff --git a/ts/binary_search.test.ts b/ts/binary_search.test.ts new file mode 100644 index 0000000..983ce6a --- /dev/null +++ b/ts/binary_search.test.ts @@ -0,0 +1,28 @@ +function binary_search(haystack: number[], needle: number): boolean { + let lo = 0; + let hi = haystack.length; + + while (lo < hi) { + const m = Math.floor(lo + (hi - lo) / 2); + const v = haystack[m]; + + if (v === needle) { + return true; + } else if (v > needle) { + hi = m; + } else { + lo = m + 1; + } + } + return false; +} + +test("test binary search", () => { + expect(binary_search([1, 2, 3, 4, 5, 6], 5)).toBe(true); + +}) + +test("test binary search can return false", () => { + expect(binary_search([1, 2, 3, 4, 5, 6], 50)).toBe(false); + +}) diff --git a/ts/bubble_sort.test.ts b/ts/bubble_sort.test.ts new file mode 100644 index 0000000..197ad01 --- /dev/null +++ b/ts/bubble_sort.test.ts @@ -0,0 +1,18 @@ +function bubble_sort(arr: number[]): void { + for (let i = 0; i < arr.length; i++) { + for (let j = 0; j < arr.length - 1; j++) { + if (arr[j] > arr[j + 1]) { + const t = arr[j+1]; + arr[j+1] = arr[j]; + arr[j] = t; + + } + } + } +} + +test("bubble sort works", () => { + const a = [2, 1, 3, 4, 5]; + bubble_sort(a); + expect(a).toEqual([1, 2, 3, 4, 5]); +}) \ No newline at end of file diff --git a/ts/linear_search.test.ts b/ts/linear_search.test.ts new file mode 100644 index 0000000..bb8d25f --- /dev/null +++ b/ts/linear_search.test.ts @@ -0,0 +1,12 @@ +function linear_search(haystack: number[], needle: number): boolean { + for (let i = 0; i < haystack.length; i++) { + if (haystack[i] === needle) { + return true; + } + } + return false; +} + +test("test linear search", () => { + expect(linear_search([1, 2, 3, 4, 5], 3)).toBe(true); +})