-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsort.ts
32 lines (27 loc) · 846 Bytes
/
sort.ts
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
import { Nominal } from '../src';
type SortedArray<T> = Nominal<'sortedArray', T[]>;
const sort = <T>(arr: T[]): SortedArray<T> => arr.sort() as SortedArray<T>;
const binarySearch = <T>(
sorted: SortedArray<T>,
search: T,
): number | undefined => {
if (sorted.length !== 0) {
const midPoint = sorted.length / 2;
if (sorted[midPoint] === search) {
return midPoint;
}
// Bang: Midpoint will exist
if (search > sorted[midPoint]!) {
return binarySearch(sorted.slice(midPoint) as SortedArray<T>, search);
} else {
return binarySearch(sorted.slice(0, midPoint) as SortedArray<T>, search);
}
} else {
return undefined;
}
};
const regularArray = [1, 7, 2, 3, 6, 9, 10, 4, 5];
// @ts-expect-error won't work
binarySearch(regularArray, 2);
// will work
binarySearch(sort(regularArray), 2);