Last active
December 26, 2017 02:44
-
-
Save SheepTester/39e4a17afc8f2076add001279ae61d55 to your computer and use it in GitHub Desktop.
Sorting algorithm that only works for positive numbers. Is it efficient? I doubt it.
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
| let arrayToSort = []; | |
| for (let i = 1000; i--;) arrayToSort.push(Math.floor(Math.random() * 1000)); // add 1000 random integers between 0-999 | |
| function arraySort(arrayToSort) { | |
| let sortedArray = [], | |
| array = []; | |
| for (let i = arrayToSort.length; i--;) { | |
| if (array[arrayToSort[i]]) array[arrayToSort[i]]++; | |
| else array[arrayToSort[i]] = 1; | |
| } | |
| for (let i = 0; i < array.length; i++) { | |
| if (array[i]) for (let j = 0; j < array[i]; j++) { | |
| sortedArray.push(i); | |
| } | |
| } | |
| return sortedArray; | |
| } | |
| /* this sorts your array AND removes its duplicates. how nice? */ | |
| function arraySortAndRemoveDuplicates(arrayToSort) { | |
| let sortedArray = [], | |
| array = []; | |
| for (let i = arrayToSort.length; i--;) array[arrayToSort[i]] = 1; | |
| for (let i = 0; i < array.length; i++) if (array[i]) sortedArray.push(i); | |
| return sortedArray; | |
| } | |
| console.log(arraySort(arrayToSort), arraySortAndRemoveDuplicates(arrayToSort)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment