Sword Finger Offer14: Upgraded Array Ordering Problem

Integer Array Sequencing Upgraded Edition Problem

Problem description

Enter an integer array and implement a function to adjust the digital 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. (All odd numbers are ordered from small to large, and all even numbers are ordered from small to large.)

Ideas for solving problems:

This problem is an extension of the previous problem. After adjusting the order of odd and even elements in an array, two sequences (odd sequence and even sequence) must be sorted separately. The idea of this problem is to adjust the odd and even elements in an array by using double pointer method, and then record the bounded subscripts of the odd and even sequence in an array. According to the subscripts, the odd sequence and even sequence belong to before and after will be sorted separately. Copy to the corresponding two temporary arrays, then sort the elements in the temporary array separately, and finally copy back the two temporary arrays.

public class Code014_02 {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        String[] inLine=sc.nextLine().split(" ");
        int len=inLine.length;
        int[] data=new int[len];
        for(int i=0;i<len;i++){
            data[i]=Integer.parseInt(inLine[i]);
        }
        ReorderOddEven(data,len);
        for(int i:data){
            System.out.print(i+" ");
        }
    }
    private static void ReorderOddEven(int[] data,int len){
        int head=0;
        int tail=len-1;
        int tmp=0;
        while (head<tail){
            if(data[head]%2==1){
                head+=1;
            }
            if(data[tail]%2==0){
                tail-=1;
            }
            if(data[head]%2==0 && data[tail]%2==1){
                tmp=data[head];
                data[head]=data[tail];
                data[tail]=tmp;
                head+=1;
                tail-=1;
            }
        }
//        System.out.println("head: "+head);
        int[] Odd= Arrays.copyOfRange(data,0,head+1);
        int[] Even=Arrays.copyOfRange(data,tail+1,len);
        Arrays.sort(Odd);
        Arrays.sort(Even);
//        System.out.println("lengthOfOdd: "+Odd.length);
//        System.out.println("lengthOfEven: "+Even.length);
//        for(int d:Odd){
//            System.out.print(d+" ");
//        }
//        for(int d:Even){
//            System.out.print(d+" ");
//        }
        for(int i=0;i<=head;i++){
            data[i]=Odd[i];
        }
        for(int i=0;i<len-head-1;i++){
            data[head+1+i]=Even[i];
        }
    }
}

Posted on Mon, 07 Oct 2019 02:34:41 -0700 by mika79