-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplementations.ts
More file actions
111 lines (95 loc) · 2.05 KB
/
implementations.ts
File metadata and controls
111 lines (95 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
export type StepState = {
result: number[];
colors?: Record<number, string>;
};
export type SortingGenerator = Generator<StepState, StepState>;
function* bubbleSort(arr: number[]): SortingGenerator {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
yield {
result: arr,
colors: {
[j]: "yellow",
[j + 1]: "green",
},
};
if (arr[j] > arr[j + 1]) {
const tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
yield {
result: arr,
colors: {
[j]: "green",
[j + 1]: "yellow",
},
};
} else {
yield {
result: arr,
colors: {
[j]: "yellow",
[j + 1]: "yellow",
},
};
}
}
}
return { result: arr };
}
function* partition(list: number[], low: number, high: number) {
const pivot = list[high];
let index = low - 1;
for (let i = low; i < high; i++) {
yield {
result: list,
colors: {
[high]: "blue",
[i]: list[i] < pivot ? "green" : "yellow",
[index]: "red",
},
};
if (list[i] < pivot) {
index++;
const tmp = list[index];
list[index] = list[i];
list[i] = tmp;
}
}
index++;
yield {
result: list,
colors: {
[index]: "red",
[high]: "green",
},
};
list[high] = list[index];
list[index] = pivot;
return index;
}
function* quickSort(
list: number[],
low: number = 0,
high: number = list.length - 1,
): SortingGenerator {
if (low < high) {
const partitionIndex = yield* partition(list, low, high);
yield* quickSort(list, low, partitionIndex - 1);
yield* quickSort(list, partitionIndex + 1, high);
}
return { result: list };
}
export const algorithms: Record<
string,
{ name: string; fn: (list: number[]) => SortingGenerator }
> = {
bubbleSort: {
name: "Bubble Sort",
fn: bubbleSort,
},
quickSort: {
name: "Quick Sort",
fn: quickSort,
},
};