Advertisement
gelita

js quick sort

Feb 18th, 2020
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  *  Quicksort
  3.  *
  4.  *  Prompt:    Given an unsorted array of integers, return the array
  5.  *             sorted using quicksort.
  6.  *
  7.  *  Input:     input {Array}
  8.  *  Output:    {Array}
  9.  *
  10.  *  Example:   [3,9,1,4,7] --> [1,3,4,7,9]
  11.  */
  12.  
  13.  
  14. // Worse Time Complexity: O(n^2)
  15. // Worse Auxiliary Space Complexity: O(n)
  16. // Average Time Complexity: O(nlogn)
  17. // Average Auxiliary Space Complexity: O(logn)
  18. //}}}
  19. function quicksort(input) {
  20.  
  21.   function divide(start, end) {
  22.     if (start >= end) { return; }
  23.    
  24.     let pivotIndex = end;
  25.     let pivot = input[pivotIndex];
  26.     let big = start;
  27.    
  28.     for (let i = start; i < end; i++) {
  29.       if (input[i] < pivot) {
  30.         swap(i, big, input);
  31.         big++;
  32.       }
  33.     }
  34.     swap(big, pivotIndex, input);
  35.    
  36.     divide(start, big - 1);
  37.     divide(big + 1, end);
  38.    
  39.   }
  40.  
  41.   divide(0, input.length - 1);
  42.   return input;
  43. }
  44.  
  45. function swap(i, j, arr) {
  46.   return [arr[i], arr[j]] = [arr[j], arr[i]];
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement