Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue #314, removed the unnecessary temp variable in shellSort.js. #620

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
68 changes: 33 additions & 35 deletions src/algorithms/sorting/shell-sort/ShellSort.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,39 @@
import Sort from '../Sort';

export default class ShellSort extends Sort {
sort(originalArray) {
// Prevent original array from mutations.
const array = [...originalArray];

// 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;

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;
}

gapShiftedIndex = currentIndex;
currentIndex -= gap;
sort(originalArray) {
// Prevent original array from mutations.
const array = [...originalArray];

// 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;

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])) {
[array[currentIndex], array[gapShiftedIndex]] = [array[gapShiftedIndex], array[currentIndex]];
}

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;
}
}
}