两个数组的归并

package org.son;

import java.lang.String;
import java.lang.System;
import java.util.Arrays;

public class Demo {
	public static void main(String[] args) {
		int[] a = { -1, 5, 9, 15, 85, 98, 100 };
		int[] b = { -2, 6, 8, 14, 73, 85, 97 };
		System.out.println(checkSort(a));
		sort(a);
		System.out.println(checkSort(a));
		System.out.println(Arrays.toString(merge(a, b)));

	}

	public static boolean checkSort(int[] a) {
		// 使用插入排序进行验证
		for (int x = 0; x < a.length - 1; x++) {
			for (int y = x; y > 0; y--) {
				if (a[y - 1] > a[y])
					return false;
			}
		}
		return true;
	}

	public static void sort(int[] a) {
		// 使用了插入排序
		for (int i = 0; i < a.length - 1; i++) {
			for (int j = i; j > 0 && a[j - 1] > a[j]; j--) {
				int temp = a[j];
				a[j] = a[j - 1];
				a[j - 1] = temp;
			}
		}
	}

	private static int[] merge(int[] a, int[] b) {
		int[] result = new int[a.length + b.length];
		if (checkSort(a) && checkSort(b)) {
			// 两个数组都处于排序状态
			int i = 0, j = 0, k = 0;
			while (i <= a.length - 1 && j <= b.length - 1) {
				// 两个数组都没有数据用完
				if (a[i] <= b[j])
					result[k++] = a[i++];
				if (b[j] < a[i])
					result[k++] = b[j++];
			}
			// a数组未用完,b数组用完了
			while (i <= a.length - 1 && j > b.length - 1) {
				result[k++] = a[i++];
			}
			// b数组未用完,a数组用完了
			while (j <= b.length - 1 && i > a.length - 1) {
				result[k++] = b[j++];
			}
		} else {
			// 如果数组a属于非排序状态则对a进行排序
			if (!checkSort(a))
				sort(a);
			// 如果数组b属于非排序状态则对b进行排序
			if (!checkSort(a))
				sort(b);
			merge(a, b);
		}
		return result;
	}
}

猜你喜欢

转载自dan326714.iteye.com/blog/2396594
今日推荐