# Array pivoting

In the quicksort algorithm the most important part is the partition step. The implementation of it, is actually not difficult, however some implementation store data on the both sides of the array, instead of just one, what leads to the more complex and error prone algorithms. In this article I would like to show that for n-partition, we need n – 1 storage indexes.

In the pivot-partitioning we just move the smaller than pivot elements on the begining of the array. We can imagine it as a stack that is growing within the array size, from the bottom to the top. Secondly, to trace the top of the stack we use a variable called storagePlace, that indicates the size of the stack and the next place where to insert an element.

```void partition(std::vector<int> & v){
int pivot = v[0]; // simplified
swap(v[0], v[v.size() - 1]);
unsigned int storagePlace = 0;
for(int i = 1; i < v.size() - 1; i++)
if(v[i] < pivot)swap(v[i], v[storagePlace++]);
swap(v[storagePlace], v[v.size() - 1]);
}
```

There is a famous problem of dutch flag described firstly by Dijkstra. Imagine that we have 3 kind of elements, let’s say negative numbers, 0s, positive numbers. We want to partition the array in the way that negative numbers go first, then 0s and finally positive. A while ago we mentioned that we can imagine pivoting as maintaining a stack within the array. We extend this idea to maintain two stacks now: one grows from the bottom to the top, and the other from the top to the bottom. The former stores negative numbers, the latter positives.

```void dutch_flag_partition(std::vector<int> & v){
int top = v.size() - 1;
int bottom = 0;
for(int i = 0; i <= top; i++){
if(v[i] < 0)swap(v[bottom++], v[i]);
else if(v[i] > 0)swap(v[top--], v[i]);
}
}
```

In this case we might be sure that the elements between [0, bottom) are already the negative numbers, between [bottom, i) we have only 0, between (top, v.size()) we have positive elements. The uknown part remains between [i, top].

Both solution offer O(n) complexity for the problem. In the second case there is no stable solution that would have O(n) complexity. However if you need to keep it stable, take a look at this article.