forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorted-linked-list.ts
43 lines (37 loc) · 1.08 KB
/
sorted-linked-list.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
33
34
35
36
37
38
39
40
41
42
43
import { Compare, defaultCompare, defaultEquals, ICompareFunction, IEqualsFunction } from '../util';
import LinkedList from './linked-list';
export default class SortedLinkedList<T> extends LinkedList<T> {
constructor(
protected equalsFn: IEqualsFunction<T> = defaultEquals,
protected compareFn: ICompareFunction<T> = defaultCompare
) {
super(equalsFn);
}
push(element: T) {
if (this.isEmpty()) {
super.push(element);
} else {
const index = this.getIndexNextSortedElement(element);
super.insert(element, index);
}
}
insert(element: T, index: number = 0) {
if (this.isEmpty()) {
return super.insert(element, 0);
}
index = this.getIndexNextSortedElement(element);
return super.insert(element, index);
}
private getIndexNextSortedElement(element: T) {
let current = this.head;
let i = 0;
for (; i < this.size() && current; i++) {
const comp = this.compareFn(element, current.element);
if (comp === Compare.LESS_THAN) {
return i;
}
current = current.next;
}
return i;
}
}