Skip to content

Added sorting algorithm to Sorts folder #1436

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

Closed
wants to merge 4 commits into from
Closed
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
48 changes: 48 additions & 0 deletions Sorts/DerpySort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/* Derpy Sort is an algorithm to randomly sort an array. It
* randomly removes and re-adds elements in an array.

* The big O on the Derpy Sort is O(N).
*
* In the Derpy Sort, we iterate through the length of the array and select a random
* index. We then remove the element associated with that index and re-add it to the
* end of the array. After the length of the array has been iterated through, the
* function then returns the resulting array.
*
* This sorting function is impractical and does not provide any purpose other than
* creating a jumbled mess. It is closest related to the Bogosort.
*
* https://en.wikipedia.org/wiki/Bogosort
*/

function derpySort(arr) {

let sorted = [];
let length = arr.length;

while (length > 0) {

// Get a random index from the array
let randomIndex = Math.floor(Math.random() * length);

// Remove the element
let element = arr.splice(randomIndex, 1)[0];

// Add it back into the array
sorted.push(element); // Add the element to the sorted array

length--;

}

return sorted;

}


let unsortedArray = [42, 17, 8, 99, 23, 54];

console.log("Original Array: " + unsortedArray);

let sortedArray = derpySort(unsortedArray);

console.log("Derpy Sorted Array: " + sortedArray);