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.
public class Solution { public void sortColors(int[] A) { // Similar to Quick3way sort but without recursion int lt = 0, gt = A.length-1; int i = 0; while (i <= gt) { if (A[i] == 0) swap(A, i++, lt++); else if (A[i] == 2) swap(A, i, gt--); else i++; } } private void swap(int[] A, int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } }
No comments:
Post a Comment