diff --git a/01_introduction_to_algorithms/ts/01_binary_search.ts b/01_introduction_to_algorithms/ts/01_binary_search.ts new file mode 100644 index 0000000..bcd8e20 --- /dev/null +++ b/01_introduction_to_algorithms/ts/01_binary_search.ts @@ -0,0 +1,24 @@ +function binary_search(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 diff --git a/02_selection_sort/ts/01_selection_sort.ts b/02_selection_sort/ts/01_selection_sort.ts new file mode 100644 index 0000000..9809f91 --- /dev/null +++ b/02_selection_sort/ts/01_selection_sort.ts @@ -0,0 +1,27 @@ +function findSmallestIndex(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(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]