Skip to content

Instantly share code, notes, and snippets.

@vaidehijoshi
Last active July 30, 2024 05:35
Show Gist options
  • Save vaidehijoshi/d696b2af5e3f068eea8066eaa75891c3 to your computer and use it in GitHub Desktop.
Save vaidehijoshi/d696b2af5e3f068eea8066eaa75891c3 to your computer and use it in GitHub Desktop.
// The partition() method takes a list of items, and a left
// reference, as well as a right reference. Both left and right
// are indexes to indicate where the pointers should start.
function partition(items, left, right) {
// Find the pivot by adding the two indexes together
// and dividing by two (the middle element, effectively).
var pivot = items[Math.floor((right + left) / 2)];
var l = left;
var r = right;
console.log('** pivot is: ', pivot);
console.log('** left is: ', items[left]);
console.log('** right is: ', items[right]);
// Once the left reference is greater than the right reference,
// we have finished sorting this set of items, and we can return.
while (l <= r) {
// If the left pointer is less than the pivot, increment it.
// In other words, move the pointer to the right.
while (items[l] < pivot) {
l++;
console.log('l is now pointing to: ', items[l]);
}
// If the right pointer is greater than the pivot, decrement it.
// In other words, move the pointer to the left.
while (items[r] > pivot) {
r--;
console.log('r is now pointing to: ', items[r]);
}
// If the left pointer is larger than the pivot, and the right
// pointer is not bigger than the pivot, swap the two elements.
if (l <= r) {
console.log('** now swapping l and r pointers: ', items[l], items[r]);
swap(items, l, r);
// After swapping, increment/decrement the pointers respectively.
l++;
r--;
// console.log('l is now pointing to: ', items[l]);
// console.log('r is now pointing to: ', items[r]);
}
}
// The left item becomes the new pivot element.
return l;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment