From 3f306706c828778a94e83e8f65a035fc34f2a553 Mon Sep 17 00:00:00 2001 From: Vasily Guzov Date: Sun, 22 Sep 2024 11:19:32 +0300 Subject: [PATCH] [solution] insertion sort for string --- lib/insertionsort.ts | 49 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 lib/insertionsort.ts diff --git a/lib/insertionsort.ts b/lib/insertionsort.ts new file mode 100644 index 0000000..fcb5185 --- /dev/null +++ b/lib/insertionsort.ts @@ -0,0 +1,49 @@ +const STR = "insertionsort"; +const SORT_STR = "eiinnoorrsstt"; +const NUMB = [12, -2, 55, 68, 80]; +const SORT_NUMB = [-2, 12, 55, 68, 80]; + +function swapCharsInString(str: string, i: number, j: number) { + return ( + str.substring(0, i) + + str[j] + + str.substring(i + 1, j) + + str[i] + + str.substring(j + 1) + ); +} + +const swapElements = (arr: number[], index1: number, index2: number) => { + [arr[index1], arr[index2]] = [arr[index2], arr[index1]]; +}; + +export function insertionSort(str: string): string; +export function insertionSort(arr: number[]): number[]; + +export function insertionSort(sortItems: string | number[]) { + let L: number, R: number; + + for (L = 1; L < sortItems.length; L++) { + R = L; + + while (R > 0 && sortItems[R] < sortItems[R - 1]) { + const index1 = R; + const index2 = R - 1; + + if (typeof sortItems === "string") { + sortItems = swapCharsInString(sortItems, index2, index1); + } + + if (Array.isArray(sortItems)) { + swapElements(sortItems, index1, index2); + } + + R = R - 1; + } + } + + return sortItems; +} + +console.log(insertionSort(STR), SORT_STR); +console.log(insertionSort(NUMB), SORT_NUMB);