Lomuto Partition Scheme

The Lomuto Partition Scheme is very similar to the simple sort function that we implemented earlier. The difference is that once we select the last element as the pivot, we need to keep adjusting its position by sorting and swapping the elements in memory, as shown in the following code:

partitionLomuto(data, low, high) {

// Take pivot as the high value
var pivot = high;

// initialize loop pointer variable
var i = low;

// loop over all values except the last (pivot)
for(var j = low; j < high - 1; j++) {

// if value greater than pivot
if (data[j].pages >= data[pivot].pages) {

// swap data
this.swap(data, i , j);

// increment pointer
i++;
}
}

// final swap to place pivot at correct
// position by swapping
this.swap(data, i, j);

// return pivot position
return i;
}

For example, let's consider the following data: 

[{pages: 20}, {pages: 10}, {pages: 1}, {pages: 5}, {pages: 3}]

When we call our partition with this dataset, our pivot is first the last element 3 (indicating pages: 3), the low value is 0 (so is our pointer) and high value is 4 (the index of the last element).

Now, in the first iteration, we see that the value of the jth element is greater than the pivot, so we swap the jth value with the low current pointer position; since both of them are the same, nothing happens on the swap, but we do increment the pointer. So, the dataset remains the same:

20, 10, 1, 5, 3
pointer: 1

In the next iteration, the same thing happens:

20, 10, 1, 5, 3
pointer: 2

In the third iteration, the value is smaller, so nothing happens and the loop continues:

20, 10, 1, 5, 3
pointer: 2

In the fourth iteration, the value (5) is greater than the pivot value, so the values swap and the pointer increments:

20, 10, 5, 1, 3
pointer: 3

Now, the control breaks out of the for loop, and we finally place our data in the correct position by swapping for the pivot one last time, which gives us the following:

20, 10, 5, 3, 1

After this, we can return the position of the pointer, which is nothing but the new position of the pivot. In this example, the data is sorted in the first iteration, but there can, and will, be scenarios where such is not the case, hence we repeat the process recursively for the subsets to the left and right of the pivot position.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.74.87