Guest User

Untitled

a guest
Jun 19th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. Pseudocode:
  2. 1. Divide by choosing any element in the subarray array[p..r].
  3. Call this element the pivot. Rearrange the elements in array[p..r] so that all elements in array[p..r]
  4. that are less than or equal to the pivot are to its left and all elements that are greater than the pivot
  5. are to the its right. We call this procedure partitioning. At this point, it doesn't matter what order
  6. the elements to the left of the pivot are in relation to each other, and the same holds for the elements
  7. to the right of the pivot. We just care that each element is somewhere on the correct side of the pivot.
  8. As a matter of practice, we'll always choose the rightmost element in the subarray, array[r], as the pivot.
  9.  
  10. 2. Conquer by recursively sorting the subarrays array[p..q-1]
  11. (all elements to the left of the pivot, which must be less than or equal to the pivot)
  12. and array[q+1..r] (all elements to the right of the pivot, which must be greater than the pivot).
  13.  
  14. 3. Combine by doing nothing. Once the conquer step recursively sorts, we are done.
  15. Why? All elements to the left of the pivot, in array[p..q-1], are less than or equal to the pivot and are sorted,
  16. and all elements to the right of the pivot, in array[q+1..r], are greater than the pivot and are sorted.
  17. The elements in array[p..r] can't help but be sorted!
  18.  
  19. Javscript code:
  20.  
  21. // Swaps two items in an array, changing the original array
  22. var swap = function(array, firstIndex, secondIndex) {
  23. var temp = array[firstIndex];
  24. array[firstIndex] = array[secondIndex];
  25. array[secondIndex] = temp;
  26. };
  27.  
  28. var partition = function(array, p, r) {
  29. var q = p;
  30.  
  31. // Compare array[j] with array[r], for j = p, p+1,...r-1
  32. // maintaining that:
  33. // array[p..q-1] are values known to be <= to array[r]
  34. // array[q..j-1] are values known to be > array[r]
  35. // array[j..r-1] haven't been compared with array[r]
  36. // If array[j] > array[r], just increment j.
  37. // If array[j] <= array[r], swap array[j] with array[q],
  38. // increment q, and increment j.
  39. for (var j = p; j < r; j++) {
  40. if (array[j] <= array[r]) {
  41. swap(array, j, q);
  42. q++;
  43. }
  44. }
  45.  
  46. // Once all elements in array[p..r-1]
  47. // have been compared with array[r],
  48. // swap array[r] with array[q], and return q.
  49. swap(array, r, q);
  50. return q;
  51. };
Add Comment
Please, Sign In to add comment