QuickSort Algorithm

Implements the QuickSort algorithm in Python

  1. // ==UserScript==
  2. // @name QuickSort Algorithm
  3. // @description Implements the QuickSort algorithm in Python
  4. // @match *://*/*
  5. // @version 0.0.1.20240417150038
  6. // @namespace https://greasyfork.org/users/1289520
  7. // ==/UserScript==
  8.  
  9. function quicksort(arr) {
  10. if (arr.length <= 1) {
  11. return arr;
  12. }
  13. const pivot = arr[Math.floor(arr.length / 2)];
  14. const left = [];
  15. const middle = [];
  16. const right = [];
  17. arr.forEach(element => {
  18. if (element < pivot) {
  19. left.push(element);
  20. } else if (element > pivot) {
  21. right.push(element);
  22. } else {
  23. middle.push(element);
  24. }
  25. });
  26. return quicksort(left).concat(middle, quicksort(right));
  27. }
  28.  
  29. // Example usage:
  30. const arr = [3, 6, 8, 10, 1, 2, 1];
  31. console.log(quicksort(arr));