`

java-54- 调整数组顺序使奇数位于偶数前面

 
阅读更多
import java.util.Arrays;
import java.util.Random;

import ljn.help.Helper;


public class OddBeforeEven {

	/**
	 * Q 54 调整数组顺序使奇数位于偶数前面
	 * 输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。要求时间复杂度为O(n)。
	 * update at 2012-04-20:
	 * "quickSort" is O(nlgn).So it does not work
	 * Now we trade space for time.
	 * Create another array which has the same length as the array to be sorted.
	 * Odd number is inserted from front,Even number from tail.
	 */
	public static void main(String[] args) {

		int[] x=new int[10];
		for(int i=0;i<10;i++){
			x[i]=i;
		}
		System.out.println(Arrays.toString(x));
		sort2(x);
		System.out.println(Arrays.toString(x));
		System.out.println("================================");
		rearrange(x);
		System.out.println(Arrays.toString(x));
		sort(x);
		System.out.println(Arrays.toString(x));
	}

	//O(n)--Odd number is inserted from front,Even number from tail.
	public static void sort(int[] x){
		if(x==null||x.length==0){
			return;
		}
		int len=x.length;
		int[] tmp=new int[len];
		int oddPos=0;
		int evenPos=len-1;
		for(int i=0;i<len;i++){
			if(!isEven(x[i])){
				tmp[oddPos++]=x[i];
			}else{
				tmp[evenPos--]=x[i];
			}
		}
		System.arraycopy(tmp, 0, x, 0, len);
	}
	
	//O(nlgn)--like Quick Sort.Find a even from the beginning and a odd from the last.Swap them.
	public static void sort2(int[] x){
		if(x==null||x.length==0){
			return;
		}
		int len=x.length;
		int i=0;
		int j=len-1;
		while(i<j){
			if(!isEven(x[i])){
				i++;
				continue;
			}
			if(isEven(x[j])){
				j--;
				continue;
			}
			if(isEven(x[i])&&!isEven(x[j])){
				Helper.swap(x,i,j);
			}
			
		}
	}
	public static boolean isEven(int x){
		return (x&1)==0;
	}
/*
20120423 update
1. for i:=1 to n do swap(a[i], a[random(1,n)]);  // 凑合,但不是真正随机
2. for i:=1 to n do swap(a[i], a[random(i,n)]);   // 真正的随机算法
其中,random(a,b)函数用于返回一个从a到b(包括a和b)的随机整数。
*/
	public static void rearrange(int[] x){
		int len=x.length;
		for(int i=0;i<len;i++){
			int j=new Random().nextInt(len);
			Helper.swap(x, i, j);
		}
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics