13.奇数位于偶数之前

奇数在前偶数在后

public class Main {
	public static void func(int[] arr) {
		int i = 0;
		int j = arr.length-1;
		while(i<j){
			while(i<j && arr[i]%2 != 0) {
				i++;
			}
			//i下标对应为一个偶数
			while(i<j && arr[j]%2 == 0) {
				j--;
			}
			//j下标对应为一个奇数
			int temp = arr[i];
			arr[i] = arr[j];
			arr[j] = temp;
		}
	}
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5,6};
		func(arr);
		for(int x:arr)
			System.out.print(x+" ");
	}
}

偶数在前奇数在后

public class Main {
	public static void func(int[] arr) {
		int i = 0;
		int j = arr.length-1;
		while(i<j){
			while(i<j && arr[i]%2 == 0) {
				i++;
			}
			while(i<j && arr[j]%2 != 0) {
				j--;
			}
			int temp = arr[i];
			arr[i] = arr[j];
			arr[j] = temp;
		}
	}
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5,6};
		func(arr);
		for(int x:arr)
			System.out.print(x+" ");
	}
}

你可能感兴趣的:(蓝桥杯省赛(Java组),java,排序算法,算法)