diff --git a/src/sort/shell/shellSort.spec.ts b/src/sort/shell/shellSort.spec.ts new file mode 100644 index 0000000..d192374 --- /dev/null +++ b/src/sort/shell/shellSort.spec.ts @@ -0,0 +1,30 @@ +import shellSort from './shellSort'; + +describe('shell sort', () => { + it('should return an empty array when the array for sorting is empty', () => { + const arrayToSort: number[] = []; + const expectedArray: number[] = []; + expect(shellSort(arrayToSort)) + .toEqual(expectedArray); + }); + + it('should return an array with the element', () => { + const arrayToSort: number[] = [14]; + const expectedArray: number[] = [14]; + expect(shellSort(arrayToSort)) + .toEqual(expectedArray); + }); + + it('should return an array with two elements sorted from lowest to highest', () => { + const arrayToSort = [65, 43]; + const expectedArray = [43, 65]; + expect(shellSort(arrayToSort)) + .toEqual(expectedArray); + }); + + it('should return an array sorted from lowest to highest', () => { + const arrayToSort = [43, 65, 44, 12, 67, 1, 9, 33, 21]; + const expectedArray = [1, 9, 12, 21, 33, 43, 44, 65, 67]; + expect(shellSort(arrayToSort)).toEqual(expectedArray); + }); +}); diff --git a/src/sort/shell/shellSort.ts b/src/sort/shell/shellSort.ts new file mode 100644 index 0000000..05483f3 --- /dev/null +++ b/src/sort/shell/shellSort.ts @@ -0,0 +1,19 @@ +export default function shellSort(array: number[]): number[] { + const introducedArray = array; + const n = introducedArray.length; + + for (let gap = Math.floor(n / 2); gap > 0; gap = Math.floor(gap / 2)) { + for (let i = gap; i < n; i += 1) { + const temp = introducedArray[i]; + + let j; + for (j = i; j >= gap && introducedArray[j - gap] > temp; j -= gap) { + introducedArray[j] = introducedArray[j - gap]; + } + + introducedArray[j] = temp; + } + } + + return introducedArray; +}