|
1 | 1 | import {SortDirection} from "./Enums";
|
2 | 2 |
|
3 | 3 | function insertionSort<T>(elementsList: T[], direction: SortDirection = SortDirection.ASC): void {
|
| 4 | + const condition: <T>(comparedElement: T, selectedElement: T) => boolean = direction === SortDirection.ASC ? ascendingCondition : descendingCondition; |
4 | 5 | for (let selectedElementIndex: number = 1; selectedElementIndex < elementsList.length; selectedElementIndex++) {
|
5 | 6 | const key: T = elementsList[selectedElementIndex];
|
6 | 7 | let comparedElementIndex: number = selectedElementIndex - 1;
|
7 |
| - while (comparedElementIndex >= 0 && elementsList[comparedElementIndex] > key) { |
| 8 | + while (comparedElementIndex >= 0 && condition(elementsList[comparedElementIndex], key)) { |
8 | 9 | elementsList[comparedElementIndex + 1] = elementsList[comparedElementIndex];
|
9 | 10 | comparedElementIndex--;
|
10 | 11 | }
|
11 | 12 | elementsList[comparedElementIndex + 1] = key;
|
12 | 13 | }
|
13 | 14 | }
|
14 | 15 |
|
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