Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
33 changes: 33 additions & 0 deletions sorts/test/tree_sort.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});



18 changes: 18 additions & 0 deletions sorts/tree_sort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @author : tamaf96<https://github.com/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 <https://en.wikipedia.org/wiki/Tree_sort>
*/

import { BinarySearchTree } from "../data_structures/tree/binary_search_tree";

export const treeSort = <T>(arr: T[]): T[] => {
const searchTree = new BinarySearchTree<T>();
for (const item of arr) {
searchTree.insert(item);
}
return searchTree.inOrderTraversal();
};