1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| public class Jz21_3 { public static void main(String[] args) { System.out.println("奇数排在前面"); System.out.println(Arrays.toString(reOrderArray(new int[]{2, 4, 6, 5, 7}, Jz21_3::isOdd))); System.out.println(Arrays.toString(reOrderArray(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, Jz21_3::isOdd)));
System.out.println("偶数排在前面"); System.out.println(Arrays.toString(reOrderArray(new int[]{2, 4, 6, 5, 7}, Jz21_3::isEven))); System.out.println(Arrays.toString(reOrderArray(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, Jz21_3::isEven)));
System.out.println("能被3整除的在前面"); System.out.println(Arrays.toString(reOrderArray(new int[]{2, 4, 6, 5, 7}, Jz21_3::isThreeTime))); System.out.println(Arrays.toString(reOrderArray(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, Jz21_3::isThreeTime))); }
public static int[] reOrderArray(int[] array, Predicate<Integer> predicate) {
if (array == null || array.length == 0) { return array; }
int left = 0; int right = array.length - 1; while (left < right) { while (left < right && predicate.test(array[left])) { left++; }
while (left < right && !predicate.test(array[right])) { right--; } if (left < right) { swap(array, left, right); } } return array; }
private static boolean isOdd(int i) { return i % 2 == 1; }
private static boolean isEven(int i) { return i % 2 == 0; }
private static boolean isThreeTime(int i) { return i % 3 == 0; }
private static void swap(int[] array, int i, int j) { int tmp = array[i]; array[i] = array[j];
array[j] = tmp; } }
|