Given an array with n objects colored red, white or blue, sort them in-place 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.
Note: You are not suppose to use the library’s sort function for this problem.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.
Could you come up with a one-pass algorithm using only constant space?
Solution Code
public class Code_NetherlandFlag {
public static void partition(int[] arr, int L, int R, int num) {
if(arr == null) return;
int less = L - 1;
int more = R + 1;
int cur = L;
while(cur < more) {
if(arr[cur] < num) {
swap(arr, cur++, ++less);
}else if(arr[cur] > num) {
swap(arr, cur, --more);
}else {
cur++;
}
}
}
public static void swap(int[] arr, int i, int j) {
if(arr == null) return;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void printArray(int[] arr) {
if(arr == null) return;
for(int i=0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
//test
public static void main(String[] args) {
int[] arr = {23, 34, 32, 5, 0, 1, 5, 4, 7, 6, 9};
partition(arr, 0, arr.length-1, 9);
printArray(arr);
}
}
6 7 5 0 1 5 4 9 32 34 23
本文介绍了一种解决荷兰国旗问题的算法,该问题要求将一个包含红、白、蓝三种颜色的对象数组进行排序,使相同颜色的对象相邻,并按红、白、蓝的顺序排列。文章提供了一个一通算法,使用常数空间复杂度,通过一次遍历来实现排序。
2936

被折叠的 条评论
为什么被折叠?



