Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | const STR = "insertionsort"; const SORT_STR = "eiinnoorrsstt"; const NUMB = [12, -2, 55, 68, 80]; const SORT_NUMB = [-2, 12, 55, 68, 80]; const WORDS = ["strc", "avgrs", "bds"]; const SORT_WORDS = ["avgrs", "bds", "strc"]; 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[] | string[], 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(arr: string[]): string[]; export function insertionSort(sortItems: string | number[] | string[]) { 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); console.log(insertionSort(WORDS), SORT_WORDS); |