Last active
June 12, 2016 16:19
-
-
Save bhalash/5c8bfb65d3ae7bc62668d31101e4283b to your computer and use it in GitHub Desktop.
Recursive Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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(''); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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