Skip to content

Instantly share code, notes, and snippets.

@bhalash
Last active June 12, 2016 16:19
Show Gist options
  • Select an option

  • Save bhalash/5c8bfb65d3ae7bc62668d31101e4283b to your computer and use it in GitHub Desktop.

Select an option

Save bhalash/5c8bfb65d3ae7bc62668d31101e4283b to your computer and use it in GitHub Desktop.
Recursive Sort
#!/usr/bin/env node
var sorter = function(a, b) {
if (a < b) {
return -1;
}
if (b == a) {
return 0;
}
return 1;
};
Array.prototype.recursiveSort = function(callback, index) {
var sorted = this, temp;
if (typeof(index) === 'undefined') {
index = 0;
}
if (callback(sorted[index], sorted[index + 1]) === 1) {
temp = sorted[index];
sorted[index] = sorted[index + 1];
sorted[index + 1] = temp;
index = 0;
} else {
index++;
}
if (index < sorted.length - 1) {
sorted = sorted.recursiveSort(callback, index);
}
return sorted;
};
var a = ['strawberries', 'oranges', 'peaches', 'pears', 'plums', 'apples', 'banana', 'cherry', 'grape'];
console.log('');
console.log(a.join(' '));
console.log(a.recursiveSort(sorter).join(' '));
console.log('');
#!/usr/bin/env node
var sorter = function(a, b) {
if (a < b) {
return -1;
}
if (a === b) {
return 0;
}
return 1;
}
Array.prototype.recursiveSort = function(callback, index) {
var sorted = this;
if (typeof(index) === 'undefined') {
index = 0;
}
if (callback(sorted[index], sorted[index + 1]) === 1) {
[sorted[index], sorted[index + 1]] = [sorted[index + 1], sorted[index]];
index = 0;
} else {
index++;
}
if (index < sorted.length - 1) {
sorted = sorted.recursiveSort(callback, index);
}
return sorted;
}
var a = ['strawberries', 'oranges', 'peaches', 'pears', 'plums', 'apples', 'banana', 'cherry', 'grape'];
console.log(a.recursiveSort(sorter));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment