java合并排序

package test3;


public class MergeSortTest {


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MergeSortTest test = new MergeSortTest();
		int[] source = { 9, 1, 0, 6, 7, 3, 2, 8, 3, 9, 5, 6, 1, 0, 0, 9, 6, 4,
				3 };
		int p = 0;
		int q = 18;
		test.mergeSort(source, p, q, true);
		for (int i = p; i < q + 1; i++) {
			System.out.print(source[i]);
		}
	}


	public void mergeSort(int[] source, int p, int q, boolean asc) {
		if (p < q) {
			int m = (p + q) / 2;
			mergeSort(source, p, m, asc);
			mergeSort(source, m + 1, q, asc);
			merge(source, p, m, q, asc);
		}
	}


	public void merge(int[] source, int p, int m, int q, boolean asc) {
		int l1 = m - p + 1;
		int[] subS1 = new int[l1];
		int l2 = q - m;
		int[] subS2 = new int[l2];
		for (int i = p; i <= m; i++) {
			subS1[i - p] = source[i];
		}
		for (int i = m + 1; i <= q; i++) {
			subS2[i - m - 1] = source[i];
		}
		int s1 = 0;
		int s2 = 0;
		int k = p;
		if (asc) {
			while (s1 < l1 && s2 < l2) {
				if (subS1[s1] <= subS2[s2]) {
					source[k] = subS1[s1];
					s1++;
				} else {
					source[k] = subS2[s2];
					s2++;
				}
				k++;
			}


			if (s1 == l1 && s2 != l2) {
				for (int i = s2; i < l2; i++) {
					// System.out.print("s1"+i+","+k);
					source[k] = subS2[i];
					k++;
				}
			} else if (s2 == l2 && s1 != l1) {
				for (int i = s1; i < l1; i++) {
					// System.out.print("s2"+i+","+k);
					source[k] = subS1[i];
					k++;
				}
			}
		} else {
			while (s1 < l1 && s2 < l2) {
				if (subS1[s1] <= subS2[s2]) {
					source[q - k] = subS1[s1];
					s1++;
				} else {
					source[q - k] = subS2[s2];
					s2++;
				}
				k++;
			}
			if (s1 == l1) {
				for (int i = s2; i < l2; i++) {
					source[q - k] = subS2[i];
					k++;
				}
			} else {
				for (int i = s1; i < l1; i++) {
					source[q - k] = subS1[i];
					k++;
				}
			}
		}


	}


}

你可能感兴趣的:(算法,java,排序算法)