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

Add shaker sort. #13

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
41 changes: 41 additions & 0 deletions algorithms/sorting/shaker-sort/shaker-sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* 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 shaker sort implementation in JavaScript.
* @param {Array} items An array of items to sort.
* @return {Array} The sorted array.
*/
function shakerSort(items) {
var start = 0,
end = items.length - 1,
i;

do {

for (i = end; i > 0; i--) {
if (items[i-1] >= items[i]) {
swap(items, i, i-1);
start = i + 1;
}
}

for (i = 1; i <= start; i++) {
if (items[i-1] > items[i]) {
swap(items, i, i-1);
end = i - 1;
}
}

} while (start < end);
}
39 changes: 39 additions & 0 deletions algorithms/sorting/shell-sort/shell-sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* 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 len = items.length
step = len,
i, j;

do {
step = Math.floor(step/2);
i = 0;
j = i + step;
while (j < len) {
if (items[i] > items[j]) {
swap(items, i, j);
}

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

return items;
}