Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Quicksort
- *
- * Prompt: Given an unsorted array of integers, return the array
- * sorted using quicksort.
- *
- * Input: input {Array}
- * Output: {Array}
- *
- * Example: [3,9,1,4,7] --> [1,3,4,7,9]
- */
- // Worse Time Complexity: O(n^2)
- // Worse Auxiliary Space Complexity: O(n)
- // Average Time Complexity: O(nlogn)
- // Average Auxiliary Space Complexity: O(logn)
- //}}}
- function quicksort(input) {
- function divide(start, end) {
- if (start >= end) { return; }
- let pivotIndex = end;
- let pivot = input[pivotIndex];
- let big = start;
- for (let i = start; i < end; i++) {
- if (input[i] < pivot) {
- swap(i, big, input);
- big++;
- }
- }
- swap(big, pivotIndex, input);
- divide(start, big - 1);
- divide(big + 1, end);
- }
- divide(0, input.length - 1);
- return input;
- }
- function swap(i, j, arr) {
- return [arr[i], arr[j]] = [arr[j], arr[i]];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement