Skip to content

Commit c745f5d

Browse files
VoloshchenkoAlegonSchiele
authored andcommitted
add code for chapters 1 and 2 in ts (egonSchiele#102)
1 parent d77cde9 commit c745f5d

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function binary_search<T>(list: T[], item: T): number | null {
2+
let low: number = 0;
3+
let high: number = list.length - 1;
4+
5+
while (low <= high) {
6+
let mid: number = Math.floor((low + high) / 2);
7+
let guess: T = list[mid];
8+
  if (guess === item) {
9+
return mid;
10+
}
11+
if (guess > item) {
12+
high = mid - 1;
13+
} else {
14+
low = mid + 1;
15+
}
16+
}
17+
18+
return null;
19+
}
20+
21+
const my_list = [1, 3, 5, 7, 9];
22+
23+
console.log(binary_search(my_list, 3)); // 1
24+
console.log(binary_search(my_list, -1)); // null
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
function findSmallestIndex<T>(array: T[]): number {
2+
let smallestIndex: number = 0;
3+
let smallestElement: T = array[smallestIndex];
4+
5+
for (let i: number = 1; i < array.length; i++) {
6+
if (array[i] < smallestElement) {
7+
smallestElement = array[i];
8+
smallestIndex = i;
9+
}
10+
}
11+
12+
return smallestIndex;
13+
}
14+
15+
function selectionSort<T>(array: T[]): T[] {
16+
const sortedArray: T[] = [];
17+
const length = array.length;
18+
19+
for (let i: number = 0; i < length; i++) {
20+
const smallestIndex: number = findSmallestIndex(array);
21+
sortedArray.push(array.splice(smallestIndex, 1)[0]);
22+
}
23+
24+
return sortedArray;
25+
}
26+
27+
console.log(selectionSort([5, 3, 6, 2, 10])); // [2, 3, 5, 6, 10]

0 commit comments

Comments
 (0)