Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Pseudocode:
- 1. Divide by choosing any element in the subarray array[p..r].
- Call this element the pivot. Rearrange the elements in array[p..r] so that all elements in array[p..r]
- that are less than or equal to the pivot are to its left and all elements that are greater than the pivot
- are to the its right. We call this procedure partitioning. At this point, it doesn't matter what order
- the elements to the left of the pivot are in relation to each other, and the same holds for the elements
- to the right of the pivot. We just care that each element is somewhere on the correct side of the pivot.
- As a matter of practice, we'll always choose the rightmost element in the subarray, array[r], as the pivot.
- 2. Conquer by recursively sorting the subarrays array[p..q-1]
- (all elements to the left of the pivot, which must be less than or equal to the pivot)
- and array[q+1..r] (all elements to the right of the pivot, which must be greater than the pivot).
- 3. Combine by doing nothing. Once the conquer step recursively sorts, we are done.
- 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,
- and all elements to the right of the pivot, in array[q+1..r], are greater than the pivot and are sorted.
- The elements in array[p..r] can't help but be sorted!
- Javscript code:
- // Swaps two items in an array, changing the original array
- var swap = function(array, firstIndex, secondIndex) {
- var temp = array[firstIndex];
- array[firstIndex] = array[secondIndex];
- array[secondIndex] = temp;
- };
- var partition = function(array, p, r) {
- var q = p;
- // Compare array[j] with array[r], for j = p, p+1,...r-1
- // maintaining that:
- // array[p..q-1] are values known to be <= to array[r]
- // array[q..j-1] are values known to be > array[r]
- // array[j..r-1] haven't been compared with array[r]
- // If array[j] > array[r], just increment j.
- // If array[j] <= array[r], swap array[j] with array[q],
- // increment q, and increment j.
- for (var j = p; j < r; j++) {
- if (array[j] <= array[r]) {
- swap(array, j, q);
- q++;
- }
- }
- // Once all elements in array[p..r-1]
- // have been compared with array[r],
- // swap array[r] with array[q], and return q.
- swap(array, r, q);
- return q;
- };
Add Comment
Please, Sign In to add comment