From 6d8592a52a7b8f54d7cb1736b1dfb70e4a867822 Mon Sep 17 00:00:00 2001 From: daadaadaah Date: Mon, 4 Jan 2021 02:41:10 +0900 Subject: [PATCH] Implment InsertSort --- .../Sort/daadaadaah/InsertSort.test.js" | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 "\354\236\220\353\243\214\352\265\254\354\241\260/Sort/daadaadaah/InsertSort.test.js" diff --git "a/\354\236\220\353\243\214\352\265\254\354\241\260/Sort/daadaadaah/InsertSort.test.js" "b/\354\236\220\353\243\214\352\265\254\354\241\260/Sort/daadaadaah/InsertSort.test.js" new file mode 100644 index 0000000..8a76c24 --- /dev/null +++ "b/\354\236\220\353\243\214\352\265\254\354\241\260/Sort/daadaadaah/InsertSort.test.js" @@ -0,0 +1,45 @@ +const getInsertIndex = (array, currentIndex) => { + let insertIndex = 0; + + for (let j = currentIndex - 1; j >= 0; j--) { + if(array[j] < array[currentIndex]) { + insertIndex = j+1; + break; + } + } + + return insertIndex; +} + +const getTempInsertSortArray = (array, insertIndex, currentIndex) => { + const currentElement = array[currentIndex]; + + for(let k = currentIndex; k >= insertIndex + 1; k--) { + array[k] = array[k-1]; + } + + array[insertIndex] = currentElement; + + return array; +} + + +const insertSort = (array) => { + for (let i = 1; i < array.length; i++) { + const currentIndex = i; + + const insertIndex = getInsertIndex(array, currentIndex); + + array = getTempInsertSortArray(array, insertIndex, currentIndex) + } + + return array; +} + +test('insertSort', () => { + expect(insertSort([5, 2])).toEqual([2, 5]); + expect(insertSort([3, 5, 2])).toEqual([2, 3, 5]); + expect(insertSort([5, 2, 3, 4, 1,])).toEqual([1,2,3,4,5]); + expect(insertSort([4, 7, 2, 3, 6, 1, 5, 8])).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); + +});