Array partition with two pointers


Some problem are using this template with minor alternation, such as:
Quick Sort
Partition Array
Sort Letters by Case
Sort Colors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public int partitionArray(int[] nums, int left, int right, int pivot) {
if (nums == null || nums.length == 0) {
return 0;
}

if (left <= right || left > 0 || right >= nums.length) {
return 0;
}

int leftPointer = left;
int rightPointer = right;

while (leftPointer < rightPointer) {
while (nums[leftPointer] < pivot && leftPointer < right) {
leftPointer++;
}
while (nums[rightPointer] >= pivot && rightPointer > left) {
rightPointer--;
}

// some condition of this swap
swap(nums, leftPointer, rightPointer);
}
// some condition of this swap
swap(nums, leftPointer, rightPointer);

// decide whether to return the position of this pivot
return rightPointer + 1;
}

public void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}