Skip to content

Commit 519175c

Browse files
authored
algorithm: gnome sort (#64)
1 parent 07b1404 commit 519175c

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

Sorts/GnomeSort.ts

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @function GnomeSort
3+
* @description Gnome sort is a sort algorithm that moving an element to its proper place is accomplished by a series of swap
4+
* @param {number[]} arr - The input array
5+
* @return {number[]} - The sorted array.
6+
* @see [GnomeSort] https://en.wikipedia.org/wiki/Gnome_sort
7+
* @example gnomeSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
8+
*/
9+
10+
export const gnomeSort = (arr: number[]): number[] => {
11+
if (arr.length <= 1) {
12+
return arr;
13+
}
14+
15+
let i: number = 1;
16+
17+
while (i < arr.length) {
18+
if (arr[i - 1] <= arr[i]) {
19+
i++; //increment index if sub-array[0:i] already sorted
20+
} else {
21+
[arr[i], arr[i - 1]] = [arr[i - 1], arr[i]]; //swapping two numbers
22+
i = Math.max(1, i - 1); //go back to the previous index to check the swapped number
23+
}
24+
}
25+
return arr;
26+
};

Sorts/test/GnomeSort.test.ts

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { gnomeSort } from '../GnomeSort';
2+
3+
describe('Testing Gnome sort', () => {
4+
const testCases: number[][] = [
5+
[],
6+
[2, 1],
7+
[8, 3, 5, 9, 1, 7, 4, 2, 6],
8+
[9, 8, 7, 6, 5, 4, 3, 2, 1],
9+
[1, 2, 3, 4, 5, 6, 7, 8, 9],
10+
[1, 1, 1, 1, 1, 1, 1, 1, 1],
11+
];
12+
13+
test.each(testCases)(
14+
'should return the correct value for test case: %#',
15+
(...arr: number[]) => {
16+
expect(gnomeSort([...arr])).toStrictEqual(
17+
[...arr].sort((a: number, b: number) => a - b)
18+
);
19+
}
20+
);
21+
});

0 commit comments

Comments
 (0)