/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { private static int partition3(int[] a){ // invariant: [ even | i ... j | uneven ] int front = 0; int back = a.length - 1; int comps = 0; // no tmp array!! int tmp; while (front < back){ comps += 2; // every time we test a[front], and sometimes a[back] too. if (a[front] % 2 == 0){ front++; comps--; // we're not testing a[back]. } else if (a[back] % 2 == 1){ back--; } else { // number at front is uneven and number at back is even tmp = a[front]; a[front] = a[back]; a[back] = tmp; front++; back--; } } return comps; } private static int partitionR(int[] a){ int front = 0; int back = a.length - 1; int comps = 0; // no tmp array!! while (front < back){ comps++; while (front < back && (a[front] & 1) == 0) { front++; if (front < back) { comps++; } } if (front < back) { comps++; } while (front < back && (a[back] & 1) == 1) { back--; if (front < back) { comps++; } } // swap the back evennumber with the odd front number // occasionally front may == back. int tmp = a[front]; a[front] = a[back]; a[back] = tmp; front++; back--; } return comps; } int[][] tests = { {1,3,5,7,9,11,13,15,17,19}, {1,2,3,4,5,6,7,8,9,10}, {2,4,6,8,10,12,14,16} }; for (int[] data : tests) { int c3 = partition3(copy3); int cR = partitionR(copyR); System.out.printf("Input data %s\n 3 gives %d comps with output %s\n R gives %d comps with output %s\n", } } }
Standard input is empty
Input data [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] 3 gives 18 comps with output [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] R gives 10 comps with output [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] Input data [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 3 gives 12 comps with output [10, 2, 8, 4, 6, 5, 7, 3, 9, 1] R gives 10 comps with output [10, 2, 8, 4, 6, 5, 7, 3, 9, 1] Input data [2, 4, 6, 8, 10, 12, 14, 16] 3 gives 7 comps with output [2, 4, 6, 8, 10, 12, 14, 16] R gives 7 comps with output [2, 4, 6, 8, 10, 12, 14, 16]