adds bubble sort

This commit is contained in:
ergz
2023-06-27 20:05:57 -07:00
parent 2ade90abc6
commit 2fef9a3d05
3 changed files with 58 additions and 0 deletions

28
ts/binary_search.test.ts Normal file
View File

@@ -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);
})

18
ts/bubble_sort.test.ts Normal file
View File

@@ -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]);
})

12
ts/linear_search.test.ts Normal file
View File

@@ -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);
})