Counting sort
two pointers
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
//法一: counting sort
public class Solution {
public void sortColors(int[] A) {
int[] count = new int[3];
for (int i = 0; i < A.length; i++) {
count[A[i]]++;
}
int i = 0;
for (int j = 0; j < 3; j++) {
while(count[j]-- > 0) {
A[i] = j;
i++;
}
}
}
}
//法2: two pointers
public class Solution {
public void sortColors(int[] A) {
int p0 = 0;
int i = 0;
int p2 = A.length - 1;
while (i <= p2) {
if (A[i] == 1) {
i++;
} else if (A[i] == 0) {
swap(A, p0, i);
i++;
p0++;
} else {
swap(A, i, p2);
p2--;
}
}
}
public void swap(int[] A, int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}