剑指offer面试题14-调整数组顺序使奇数位于偶数前面

题目:

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得全部奇数位于数组的前半部分。全部偶数位于数组的后半部分。


前后分的这个。,让我想起来高速排序。好吧,就用这个做。

考虑到了排序的可扩展性,这里的推断条件设置为接口。


package com.aii.algorithm;

public class ArrayAdjuster {

	public void adjust(int[] array, CallBack callBack) {
		if (array == null) {
			throw new RuntimeException();
		}

		partition(array, 0, array.length - 1, callBack);
	}

	// 在快排的基础上增加了一个接口
	private void partition(int[] array, int start, int end, CallBack condition) {
		if (array.length == 0) {
			return;
		}

		int tmp = array[start];
		int tmpIndex = start++;
		while (start < end) {
			while (start < end && !condition.event(array[end])) {
				end--;
			}
			if (start < end && condition.event(array[end])) {
				array[tmpIndex] = array[end];
				tmpIndex = end--;
			}

			//
			while (start < end && condition.event(array[start])) {
				start++;
			}
			if (start < end && !condition.event(array[start])) {
				array[tmpIndex] = array[start];
				tmpIndex = start++;
			}
		}
		array[tmpIndex] = tmp;
	}

	public interface CallBack {
		boolean event(int i);
	}
}


測试用例

package com.aii.algorithm;

import java.util.Arrays;

import org.junit.Test;

import com.aii.algorithm.ArrayAdjuster.CallBack;

public class ArrayAdjusterTest {

	@Test
	public void test() {
		int[] a = { 1, 2, 3, 4, 6, -2, -3, 0, 1, -1 };
		new ArrayAdjuster().adjust(a, new CallBack() {

			@Override
			public boolean event(int i) {
				if (i % 2 == 0) {
					return false;
				}
				return true;
			}
		});
		System.out.println(Arrays.toString(a));
	}

}

结果:
[-1, 1, 3, -3, 1, -2, 6, 0, 4, 2]




原文地址:https://www.cnblogs.com/zsychanpin/p/7102553.html