Skip to content

Add shell sort. #11

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
38 changes: 38 additions & 0 deletions algorithms/sorting/shell-sort/shell-sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Swaps two values in an array.
* @param {Array} items The array containing the items.
* @param {int} firstIndex Index of first item to swap.
* @param {int} secondIndex Index of second item to swap.
* @return {void}
*/
function swap(items, firstIndex, secondIndex){
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}

/**
* A shell sort implementation in JavaScript.
* @param {Array} items An array of items to sort.
* @return {Array} The sorted array.
*/
function shellSort(items) {
var step = items.length,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be one space between var and step.

i, j;

do {
step = Math.floor(step/2);
i = 0;
j = i + step;
while (j < arr.length) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

arr is undefined

if (items[i] > items[j]) {
swap(items, i, j);
}

i++;
j = i + step;
}
} while (step >= 1);

return items;
}