Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
30 changes: 30 additions & 0 deletions src/sort/shell/shellSort.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
19 changes: 19 additions & 0 deletions src/sort/shell/shellSort.ts
Original file line number Diff line number Diff line change
@@ -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;
}