Skip to content

Commit 8f51d11

Browse files
author
kaczor6418
committed
feat(DESC): add sort descending option
1 parent 27cd631 commit 8f51d11

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/main.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,24 @@
11
import {SortDirection} from "./Enums";
22

33
function insertionSort<T>(elementsList: T[], direction: SortDirection = SortDirection.ASC): void {
4+
const condition: <T>(comparedElement: T, selectedElement: T) => boolean = direction === SortDirection.ASC ? ascendingCondition : descendingCondition;
45
for (let selectedElementIndex: number = 1; selectedElementIndex < elementsList.length; selectedElementIndex++) {
56
const key: T = elementsList[selectedElementIndex];
67
let comparedElementIndex: number = selectedElementIndex - 1;
7-
while (comparedElementIndex >= 0 && elementsList[comparedElementIndex] > key) {
8+
while (comparedElementIndex >= 0 && condition(elementsList[comparedElementIndex], key)) {
89
elementsList[comparedElementIndex + 1] = elementsList[comparedElementIndex];
910
comparedElementIndex--;
1011
}
1112
elementsList[comparedElementIndex + 1] = key;
1213
}
1314
}
1415

15-
const examplerray = [31, 41, 59, 26, 41, 58];
16-
insertionSort(examplerray);
17-
console.log(examplerray);
16+
const ascendingCondition: <T>(comparedElement: T, selectedElement: T) => boolean = <T>(comparedElement: T, selectedElement: T) => comparedElement > selectedElement;
17+
const descendingCondition: <T>(comparedElement: T, selectedElement: T) => boolean = <T>(comparedElement: T, selectedElement: T) => comparedElement < selectedElement;
18+
19+
const exampleArray1 = [31, 41, 59, 26, 41, 58];
20+
const exampleArray2 = [31, 41, 59, 26, 41, 58];
21+
insertionSort(exampleArray1, SortDirection.ASC);
22+
insertionSort(exampleArray2, SortDirection.DESC);
23+
console.log(exampleArray1);
24+
console.log(exampleArray2);

0 commit comments

Comments
 (0)