From c745f5d2a7200ef703182ac0ded23d5b2be8ae93 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 28 Mar 2019 23:51:48 +0200 Subject: [PATCH] add code for chapters 1 and 2 in ts (#102) --- .../ts/01_binary_search.ts | 24 +++++++++++++++++ 02_selection_sort/ts/01_selection_sort.ts | 27 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 01_introduction_to_algorithms/ts/01_binary_search.ts create mode 100644 02_selection_sort/ts/01_selection_sort.ts 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]