Skip to content

Instantly share code, notes, and snippets.

@greenlaw110
Created August 22, 2017 00:15
Show Gist options
  • Save greenlaw110/cfe08c153a2abd08a1e1c86345e8ec48 to your computer and use it in GitHub Desktop.
Save greenlaw110/cfe08c153a2abd08a1e1c86345e8ec48 to your computer and use it in GitHub Desktop.
Sort an int array so that all even numbers be positioned at the left hand side of the array
/**
* The class sort int array by odd and even.
*
* The requirement is: all even number shall be at the left hand side of the array
*/
public class OddEvenSort {
public static void main(String[] args) throws Exception {
//Act.start("Hello World");
sort(new int[]{0});
sort(new int[]{1});
sort(new int[]{0, 1});
sort(new int[]{1, 0});
sort(new int[]{1, 0, 3});
sort(new int[]{1, 1, 1});
sort(new int[]{2, 1, 0, 3});
sort(new int[]{2, 1, 5, 3});
test();
}
private static void test() {
int[] array = new int[10];
Random r = new Random();
for (int i = 0; i < 10; ++i) {
array[i] = r.nextInt(100);
}
sort(array);
}
public static void sort(int[] array) {
final String SEP_LINE = "--------------------------------------";
System.out.println(Arrays.toString(array));
int len = array.length;
if (len < 2) {
System.out.println("swapped: 0");
System.out.println("iteration: 0");
System.out.println(SEP_LINE);
return;
}
int swap = 0;
int iterate = 0;
for (int i = 0, j = len - 1; i < j; ++i) {
iterate++;
if (0 != array[i] % 2) {
for (; i < j && 0 != array[j] % 2; --j,iterate++) {}
if (i < j) {
swap(array, i, j);
swap++;
}
}
}
System.out.println(Arrays.toString(array));
System.out.printf("swapped:%5d\n", swap);
System.out.printf("iteration:%3d\n", iterate);
System.out.println(SEP_LINE);
}
private static void swap(int[] array, int i, int j) {
array[i] ^= array[j];
array[j] ^= array[i];
array[i] ^= array[j];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment