Skip to content

algorithm: gnome sort #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 20, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
26 changes: 26 additions & 0 deletions Sorts/GnomeSort.ts
Original file line number Diff line number Diff line change
@@ -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++;
} else {
[arr[i], arr[i - 1]] = [arr[i - 1], arr[i]];
i = Math.max(1, i - 1);
}
}
return arr;
};
21 changes: 21 additions & 0 deletions Sorts/test/GnomeSort.test.ts
Original file line number Diff line number Diff line change
@@ -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)
);
}
);
});