Adjust the order of the array so that odd numbers come before even numbers

Title description

  • Enter an integer array and implement a function to adjust the order of the numbers in the array so that all odd numbers are in the first half of the array, and all even numbers are in the second half of the array

The general enumeration solution of algorithm problems is wrong.

Use the double pointer method to solve the problem:
we use two pointers, the first pointer points to the first number of the array, this pointer will only move backward, and the second pointer points to the last number of the array, which will only move forward . When the first pointer points to an even number and the second pointer points to an odd number, we swap the two numbers. The loop stops until the subscript of the first pointer is not less than the subscript of the second pointer.

    private static void reOrder(int[] arr) {
    
    
        if (arr == null || arr.length == 0) {
    
    
            return;
        }
        int start = 0;
        int end = arr.length - 1;
        while (start < end) {
    
    
            while (start < end && !isEven(arr[start])) {
    
    
                start++;
            }
            while (start < end && isEven(arr[end])) {
    
    
                end--;
            }
            if (start < end) {
    
    
                int temp = arr[start];
                arr[start] = arr[end];
                arr[end] = temp;
            }
        }
        System.out.println(Arrays.toString(arr));
    }

    private static boolean isEven(int num) {
    
    
        return (num & 1) == 0; // 和1相与结果为0,则这个数字是偶数
    }

Guess you like

Origin blog.csdn.net/liu_12345_liu/article/details/103445356