Advertisement
Guest User

Untitled

a guest
Sep 30th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. 'use strict'
  2.  
  3. const nums = [3, 0, 2, 5, 1, 3, 0]
  4. quicksort(nums, 0, nums.length - 1)
  5. console.log(nums)
  6.  
  7. const chars = ['z', 'a', 'u', 'f', 'f', 'A']
  8. quicksort(chars, 0, chars.length - 1)
  9. console.log(chars)
  10.  
  11. // quicksort is at worst O(n^2), on averago O(n log n)
  12. //
  13. // TODO implement a better way of choosing pivot point in order to
  14. // reduce the chance that the pivot will be the highest or lowest
  15. // value in the element, which would cause it to run be O(n^2)
  16. function quicksort (arr, lo, hi) {
  17. if (lo < hi) {
  18. const pivotIndex = partition(arr, lo, hi)
  19. quicksort(arr, lo, pivotIndex - 1) // sort the low partition
  20. quicksort(arr, pivotIndex + 1, hi) // sort the high partition
  21. }
  22. }
  23.  
  24. function partition (arr, lo, hi) {
  25. const pivot = arr[hi] // the element to compare against
  26. let wall = lo // the index to swap at
  27.  
  28. for (let i = lo; i < hi; i++) {
  29. // if the current element is less than the pivot, swap it with the
  30. // index at wall and move the wall over by one
  31. if (arr[i] < pivot) {
  32. swap(arr, i, wall)
  33. wall++
  34. }
  35. }
  36.  
  37. swap(arr, hi, wall)
  38. return wall
  39. }
  40.  
  41. function swap (arr, i, j) {
  42. const tmp = arr[i] // swap in-place O(1)
  43. arr[i] = arr[j]
  44. arr[j] = tmp
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement