Example #1
0
 // use k scan array, and keep 2 more pointers i and j
 // element in [0,i] < key
 // element in (i,j] == key
 // element in (j,k] > key
 public static void partition3Way(int[] A, int key) {
   int i = -1;
   int j = -1;
   for (int k = 0; k < A.length; k++) {
     if (A[k] > key) continue;
     else if (A[k] == key) ArrayUtil.swap(A, k, ++j);
     else {
       if (j == i) j = i + 1; // no elements equals to key
       ArrayUtil.swap(A, k, ++i);
       if (A[k] == key) ArrayUtil.swap(A, k, ++j); // swap back if prev swap put equal element to k
     }
   }
 }
Example #2
0
 public static int partitionArray(int[] nums, int k) {
   // write your code here
   int i = -1;
   for (int j = 0; j < nums.length; j++) {
     if (nums[j] < k) ArrayUtil.swap(nums, ++i, j);
   }
   return i + 1;
 }