Skip to content

Commit b94adb4

Browse files
committed
feat: examples from chapter 4
1 parent 6b087c5 commit b94adb4

2 files changed

Lines changed: 48 additions & 0 deletions

File tree

chapter-4/1_bubble_sort.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
def bubble_sort(list):
2+
unsorted_until_index = len(list) - 1
3+
sorted = False
4+
5+
while not sorted:
6+
sorted = True
7+
for i in range(unsorted_until_index):
8+
if list[i] > list[i+1]:
9+
list[i], list[i+1] = list[i+1], list[i]
10+
sorted = False
11+
unsorted_until_index -= 1
12+
return list

chapter-4/2_quadratic_problem.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
function hasDuplicateValueQuadratic(array: number[]): boolean { // this function has efficiency O(N^2), because we perform an outer loop and for each element we perform an inner loop
2+
let steps: number = 0
3+
for (let i = 0; i < array.length; i++) {
4+
for (let j = 0; j< array.length; j++) {
5+
steps++
6+
if (j !== j && array[i] === array[j]) {
7+
return true
8+
}
9+
}
10+
}
11+
console.log(steps)
12+
return false
13+
}
14+
15+
function hasDuplicateValueLinear(array: number[]): boolean { // This function has efficiency O(N), because we are only running comparisons through one loop
16+
let existingNumbers: (number | undefined)[] = [] // will be something like [undefined, 1, undefined, undefined, 1], where "1" marks the if the number in that index has been seen
17+
for (let i = 0; i < array.length; i++) {
18+
if (existingNumbers[array[i]] === 1) {
19+
return true
20+
} else {
21+
existingNumbers[array[i]] = 1
22+
}
23+
}
24+
return false
25+
}
26+
27+
function hasDuplicateValueSet(array: number[]): boolean { // In this case, you could also use a Set to check if a numbers has a duplicate
28+
const seen = new Set<number>();
29+
for (const num of array) {
30+
if (seen.has(num)) {
31+
return true;
32+
}
33+
seen.add(num);
34+
}
35+
return false;
36+
}

0 commit comments

Comments
 (0)