diff --git a/src/sort/insertion/insertionSort.spec.ts b/src/sort/insertion/insertionSort.spec.ts new file mode 100644 index 0000000..7f65509 --- /dev/null +++ b/src/sort/insertion/insertionSort.spec.ts @@ -0,0 +1,39 @@ +import insertionSort from './insertionSort'; + +const sortLowToHigh = (a: number, b: number): boolean => (a > b); +const sortHighToLow = (a: number, b: number): boolean => (a < b); + +describe('Insertion sort', () => { + it('should return an empty array when the array for sorting is empty', () => { + const arrayToSort: number[] = []; + const expectedArray: number[] = []; + expect(insertionSort(arrayToSort, sortLowToHigh)) + .toEqual(expectedArray); + }); + + it('should return an array with the element', () => { + const arrayToSort: number[] = [14]; + const expectedArray: number[] = [14]; + expect(insertionSort(arrayToSort, sortLowToHigh)) + .toEqual(expectedArray); + }); + + it('should return an array with two elements sorted from lowest to highest', () => { + const arrayToSort = [65, 43]; + const expectedArray = [43, 65]; + expect(insertionSort(arrayToSort, sortLowToHigh)) + .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(insertionSort(arrayToSort, sortLowToHigh)).toEqual(expectedArray); + }); + + it('should return an array sorted from highest to lowest', () => { + const arrayToSort = [43, 65, 44, 12, 67, 1, 9, 33, 21]; + const expectedArray = [67, 65, 44, 43, 33, 21, 12, 9, 1]; + expect(insertionSort(arrayToSort, sortHighToLow)).toEqual(expectedArray); + }); +}); diff --git a/src/sort/insertion/insertionSort.ts b/src/sort/insertion/insertionSort.ts new file mode 100644 index 0000000..6f7883b --- /dev/null +++ b/src/sort/insertion/insertionSort.ts @@ -0,0 +1,17 @@ +interface CompareFunction { + (a: number, b: number): boolean; +} + +export default function insertionSort(array: number[], comparefunction: CompareFunction): number[] { + const myArray = array; + for (let j = 0; j < myArray.length; j += 1) { + const key = myArray[j]; + let i = j - 1; + while (i >= 0 && comparefunction(myArray[i], key)) { + myArray[i + 1] = myArray[i]; + i -= 1; + } + myArray[i + 1] = key; + } + return myArray; +}