add code for chapters 1 and 2 in ts (#102)
This commit is contained in:
24
01_introduction_to_algorithms/ts/01_binary_search.ts
Normal file
24
01_introduction_to_algorithms/ts/01_binary_search.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
function binary_search<T>(list: T[], item: T): number | null {
|
||||
let low: number = 0;
|
||||
let high: number = list.length - 1;
|
||||
|
||||
while (low <= high) {
|
||||
let mid: number = Math.floor((low + high) / 2);
|
||||
let guess: T = list[mid];
|
||||
if (guess === item) {
|
||||
return mid;
|
||||
}
|
||||
if (guess > item) {
|
||||
high = mid - 1;
|
||||
} else {
|
||||
low = mid + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
const my_list = [1, 3, 5, 7, 9];
|
||||
|
||||
console.log(binary_search(my_list, 3)); // 1
|
||||
console.log(binary_search(my_list, -1)); // null
|
||||
27
02_selection_sort/ts/01_selection_sort.ts
Normal file
27
02_selection_sort/ts/01_selection_sort.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
function findSmallestIndex<T>(array: T[]): number {
|
||||
let smallestIndex: number = 0;
|
||||
let smallestElement: T = array[smallestIndex];
|
||||
|
||||
for (let i: number = 1; i < array.length; i++) {
|
||||
if (array[i] < smallestElement) {
|
||||
smallestElement = array[i];
|
||||
smallestIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
return smallestIndex;
|
||||
}
|
||||
|
||||
function selectionSort<T>(array: T[]): T[] {
|
||||
const sortedArray: T[] = [];
|
||||
const length = array.length;
|
||||
|
||||
for (let i: number = 0; i < length; i++) {
|
||||
const smallestIndex: number = findSmallestIndex(array);
|
||||
sortedArray.push(array.splice(smallestIndex, 1)[0]);
|
||||
}
|
||||
|
||||
return sortedArray;
|
||||
}
|
||||
|
||||
console.log(selectionSort([5, 3, 6, 2, 10])); // [2, 3, 5, 6, 10]
|
||||
Reference in New Issue
Block a user