Merge two arrays

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) {
		// Validate using insertion sort
		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) {
		// use insertion sort
		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)) {
			// both arrays are in sorted state
			int i = 0, j = 0, k = 0;
			while (i <= a.length - 1 && j <= b.length - 1) {
				// Both arrays are empty of data
				if (a[i] <= b[j])
					result[k++] = a[i++];
				if (b[j] < a[i])
					result[k++] = b[j++];
			}
			// The a array is not used up, the b array is used up
			while (i <= a.length - 1 && j > b.length - 1) {
				result[k++] = a[i++];
			}
			// The b array is not used up, the a array is used up
			while (j <= b.length - 1 && i > a.length - 1) {
				result[k++] = b[j++];
			}
		} else {
			// sort a if array a is in unsorted state
			if (!checkSort(a))
				sort(a);
			// sort b if array b is in unsorted state
			if (!checkSort(a))
				sort(b);
			merge (a, b);
		}
		return result;
	}
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326847804&siteId=291194637