From e32f9c0a961c5d6e44c414980ed2a28d14bbd92c Mon Sep 17 00:00:00 2001 From: Nishi Agrawal Date: Thu, 31 Dec 2020 12:48:30 +0530 Subject: [PATCH] Removed the temp variable (issue #314) from shellSort.js, enhanced the code --- .../sorting/shell-sort/ShellSort.js | 58 +++++++++---------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/src/algorithms/sorting/shell-sort/ShellSort.js b/src/algorithms/sorting/shell-sort/ShellSort.js index cdbba997..08c92306 100644 --- a/src/algorithms/sorting/shell-sort/ShellSort.js +++ b/src/algorithms/sorting/shell-sort/ShellSort.js @@ -1,41 +1,39 @@ import Sort from '../Sort'; export default class ShellSort extends Sort { - sort(originalArray) { - // Prevent original array from mutations. - const array = [...originalArray]; + sort(originalArray) { + // Prevent original array from mutations. + const array = [...originalArray]; - // Define a gap distance. - let gap = Math.floor(array.length / 2); + // Define a gap distance. + let gap = Math.floor(array.length / 2); - // Until gap is bigger then zero do elements comparisons and swaps. - while (gap > 0) { - // Go and compare all distant element pairs. - for (let i = 0; i < (array.length - gap); i += 1) { - let currentIndex = i; - let gapShiftedIndex = i + gap; + // Until gap is bigger then zero do elements comparisons and swaps. + while (gap > 0) { + // Go and compare all distant element pairs. + for (let i = 0; i < (array.length - gap); i += 1) { + let currentIndex = i; + let gapShiftedIndex = i + gap; - while (currentIndex >= 0) { - // Call visiting callback. - this.callbacks.visitingCallback(array[currentIndex]); + while (currentIndex >= 0) { + // Call visiting callback. + this.callbacks.visitingCallback(array[currentIndex]); - // Compare and swap array elements if needed. - if (this.comparator.lessThan(array[gapShiftedIndex], array[currentIndex])) { - const tmp = array[currentIndex]; - array[currentIndex] = array[gapShiftedIndex]; - array[gapShiftedIndex] = tmp; - } + // Compare and swap array elements if needed. + if (this.comparator.lessThan(array[gapShiftedIndex], array[currentIndex])) { + [array[currentIndex], array[gapShiftedIndex]] = [array[gapShiftedIndex], array[currentIndex]]; + } - gapShiftedIndex = currentIndex; - currentIndex -= gap; + gapShiftedIndex = currentIndex; + currentIndex -= gap; + } + } + + // Shrink the gap. + gap = Math.floor(gap / 2); } - } - // Shrink the gap. - gap = Math.floor(gap / 2); + // Return sorted copy of an original array. + return array; } - - // Return sorted copy of an original array. - return array; - } -} +} \ No newline at end of file