diff --git a/Sorts/GnomeSort.ts b/Sorts/GnomeSort.ts new file mode 100644 index 00000000..adfbf28b --- /dev/null +++ b/Sorts/GnomeSort.ts @@ -0,0 +1,26 @@ +/** + * @function GnomeSort + * @description Gnome sort is a sort algorithm that moving an element to its proper place is accomplished by a series of swap + * @param {number[]} arr - The input array + * @return {number[]} - The sorted array. + * @see [GnomeSort] https://en.wikipedia.org/wiki/Gnome_sort + * @example gnomeSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8] + */ + +export const gnomeSort = (arr: number[]): number[] => { + if (arr.length <= 1) { + return arr; + } + + let i: number = 1; + + while (i < arr.length) { + if (arr[i - 1] <= arr[i]) { + i++; //increment index if sub-array[0:i] already sorted + } else { + [arr[i], arr[i - 1]] = [arr[i - 1], arr[i]]; //swapping two numbers + i = Math.max(1, i - 1); //go back to the previous index to check the swapped number + } + } + return arr; +}; diff --git a/Sorts/test/GnomeSort.test.ts b/Sorts/test/GnomeSort.test.ts new file mode 100644 index 00000000..7d9ad65d --- /dev/null +++ b/Sorts/test/GnomeSort.test.ts @@ -0,0 +1,21 @@ +import { gnomeSort } from '../GnomeSort'; + +describe('Testing Gnome sort', () => { + const testCases: number[][] = [ + [], + [2, 1], + [8, 3, 5, 9, 1, 7, 4, 2, 6], + [9, 8, 7, 6, 5, 4, 3, 2, 1], + [1, 2, 3, 4, 5, 6, 7, 8, 9], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + ]; + + test.each(testCases)( + 'should return the correct value for test case: %#', + (...arr: number[]) => { + expect(gnomeSort([...arr])).toStrictEqual( + [...arr].sort((a: number, b: number) => a - b) + ); + } + ); +});