diff --git a/DIRECTORY.md b/DIRECTORY.md index 92c92ff3..de534ede 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -166,3 +166,4 @@ * [Selection Sort](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/sorts/selection_sort.ts) * [Shell Sort](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/sorts/shell_sort.ts) * [Swap Sort](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/sorts/swap_sort.ts) + * [Tree Sort](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/sorts/tree_sort.ts) diff --git a/sorts/test/tree_sort.test.ts b/sorts/test/tree_sort.test.ts new file mode 100644 index 00000000..07cbca56 --- /dev/null +++ b/sorts/test/tree_sort.test.ts @@ -0,0 +1,33 @@ +import { treeSort } from "../tree_sort"; + +describe('TreeSort (numbers)', () => { + it.each([ + { input: [], expected: [] }, + { input: [1, 18, 3, 4, -5, 6], expected: [-5, 1, 3, 4, 6, 18] }, + { input: [7, 6, 2, 5.2, 11, 0], expected: [0, 2, 5.2, 6, 7, 11] }, + { input: [3, 3, -2, 1, 0], expected: [-2, 0, 1, 3, 3] }, + { input: [3, 0, -2.4, 1, 9, 8, -7, 6], expected: [-7, -2.4, 0, 1, 3, 6, 8, 9] }, + { input: [1, 0, -14, 0, 8.6, 6, 8], expected: [-14, 0, 0, 1, 6, 8, 8.6] }, + ])('should work for given input', ({ input, expected }) => { + expect(treeSort(input)).toEqual(expected); + }); +}); + +describe('TreeSort (strings)', () => { + it.each([ + { input: ["e","egr","sse","aas", "as","abs"], expected: ["aas","abs","as","e","egr","sse"] }, + ])('should work for given input', ({ input, expected }) => { + expect(treeSort(input)).toEqual(expected); + }); +}); + +describe('TreeSort (dates)', () => { + it.each([ + { input: [new Date("2019-01-16"),new Date("2019-01-01"),new Date("2022-05-20")], expected: [new Date("2019-01-01"),new Date("2019-01-16"),new Date("2022-05-20")] }, + ])('should work for given input', ({ input, expected }) => { + expect(treeSort(input)).toEqual(expected); + }); +}); + + + \ No newline at end of file diff --git a/sorts/tree_sort.ts b/sorts/tree_sort.ts new file mode 100644 index 00000000..e4369e52 --- /dev/null +++ b/sorts/tree_sort.ts @@ -0,0 +1,18 @@ +/** + * @author : tamaf96 + * @description + * Tree Sort sorts a list by building a binary search tree and traversing it. + * @param {T[]} arr - Array of comparable items + * @return {T[]} - The sorted Array. + * @see + */ + +import { BinarySearchTree } from "../data_structures/tree/binary_search_tree"; + +export const treeSort = (arr: T[]): T[] => { + const searchTree = new BinarySearchTree(); + for (const item of arr) { + searchTree.insert(item); + } + return searchTree.inOrderTraversal(); +};