归并排序
package com.gds.ai;
import java.util.Arrays;
public class MergeSort {
protected static void merge(int[] A, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = (r - (q + 1)) + 1;
int[] L = new int[n1+1];
int[] R = new int[n2+1];
for (int i = 0; i < n1; i++) {
L[i] = A[p + i];
}
for (int j = 0; j < n2; j++) {
R[j] = A[(q + 1) + j];
}
L[n1] = Integer.MAX_VALUE;
R[n2] = Integer.MAX_VALUE;
int i = 0;
int j = 0;
for (int k = p; k < r + 1; k++) {
if (L[i] <= R[j]) {
A[k] = L[i];
i++;
} else {
A[k] = R[j];
j++;
}
}
}
protected static void sort(int[] A, int p, int r) {
if (p < r) {
int q = (int) Math.floor((p + r)/2);
MergeSort.sort(A, p, q);
MergeSort.sort(A, q+1, r);
merge(A, p, q, r);
}
}
public static void main(String[] args) {
int[] A = { 9, 5, 4, 7, 1, 3, 2, 6 };
sort(A, 0, A.length-1);
System.out.println(Arrays.toString(A));
}
}