This commit is contained in:
Antonio Eduardo Moreira 2024-07-17 10:38:19 +09:00 committed by GitHub
commit 8d5be6d048
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 77 additions and 0 deletions

View File

@ -0,0 +1,38 @@
import Sort from '../Sort';
export default class GnomeSort extends Sort {
/**
* @param {number[]} originalArray
*/
sort(originalArray) {
const sortedArray = originalArray.map(element => element);
// Variable that will be itering during loop
let index = 0;
if (sortedArray.length <= 1) {
return sortedArray;
}
// Loop for sort the array
while (index < sortedArray.length) {
// Detects the first iteration
if (index === 0) {
index += 1;
}
// Detects if the current position is smaller of previous
if (sortedArray[index] >= sortedArray[index - 1]) {
index += 1;
} else {
// Change the position of current position for before
const temp = sortedArray[index];
sortedArray[index] = sortedArray[index - 1];
sortedArray[index - 1] = temp;
index -= 1;
}
}
return sortedArray;
}
}

View File

@ -0,0 +1,25 @@
# Gnome sort
Gnome sort (dubbed stupid sort) is a sorting algorithm originally
proposed by an Iranian computer scientist Hamid Sarbazi-Azad
(professor of Computer Engineering at Sharif University of Technology)
in 2000. The sort was first called stupid sort (not to be confused
with bogosort), and then later described by Dick Grune and named gnome sort.
The gnome sort is a sorting algorithm which is similar to insertion
sort in that it works with one item at a time but gets the item to
the proper place by a series of swaps, similar to a bubble sort.
It is conceptually simple, requiring no nested loops. The average
running time is O(n2) but tends towards O(n) if the list is initially
almost sorted.
The algorithm finds the first place where two adjacent elements are
in the wrong order and swaps them. It takes advantage of the fact that
performing a swap can introduce a new out-of-order adjacent pair
next to the previously swapped elements. It does not assume that elements
forward of the current position are sorted, so it only needs to check
the position directly previous to the swapped elements.
## References
- [Wikipedia](https://en.wikipedia.org/wiki/Gnome_sort)

View File

@ -0,0 +1,14 @@
import GnomeSort from '../GnomeSort';
import {
SortTester,
} from '../../SortTester';
describe('GnomeSort', () => {
it('should sort array', () => {
SortTester.testSort(GnomeSort);
});
it('should sort negative numbers', () => {
SortTester.testNegativeNumbersSort(GnomeSort);
});
});