Offer name prove safety half 14 is inscribed: adjusting the array so that the order in front of the even-odd

Title: Enter an array of integers, to realize a function to adjust the order of the numbers in the array, such that all of the odd part of the front half of the array, all the even located in the second half of the array.

Solving idea is: maintaining two pointers, one pointing to the array element of the first start, the other pointing to the last element in the array End, two pointers are moved toward each other, when the start pointer points to an even number ++, end-- pointer to an odd number, and start <end conditions, the exchange of data on their positions until the start and end pointers collide, i.e. start> = end end.

On the code:

package com.xxx.algorithm.sort;
public class OddEvenSolution {
	public static void swap(int[] nums){
		int begin = 0,end=nums.length-1;
		while(begin<end){
			while(begin<end && (nums[begin]&1)==1){
				begin++;
			}
			while(begin < end && (nums[end]&1)==0){
				end--;
			}
			int tmp = nums[begin];
			nums[begin] = nums[end];
			nums[end] = tmp;
		}
	}
	
	public static void print(int[] nums){
		for(int i=0;i<nums.length;i++){
			System.out.print(nums[i] +" ");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		int[] arr = {1,3,2,4,5,7,8,9,0,3,5,3,5,6};
		print(arr);
		swap(arr);
		print(arr);
 	}

}

 Data exchange process is as follows:

 This is not the only solution, but relative to the common solution: directly through the array, and then the even move to the end of the array, the time complexity is much smaller.

Guess you like

Origin blog.csdn.net/feinifi/article/details/93242693