public class SortUtil {
/**
* 归并排序采用递归
* @param a
* @param n
*/
public static void Sort(int[] a, int n) {
printData(a);
mergeSort(a, 0, n - 1);
printData(a);
}
public static int[] mergeSort(int a[], int low, int hight) {
// 终止条件
if (low < hight) {
int mid = (hight + low) / 2;
mergeSort(a, low, mid);
mergeSort(a, mid + 1, hight);
merge(a, low, hight);
}
return a;
}
public static void merge(int a[], int low, int hight) {
int mid = (low + hight) / 2;
int[] temp = new int[hight - low+1];
int i = low;
int j = mid + 1;
int currentIndex = 0;
while (i <= mid && j <= hight) {
if (a[i] < a[j]) {
temp[currentIndex++] = a[i];
i++;
} else {
temp[currentIndex++] = a[j];
j++;
}
}
if (i <= mid) {
for (; i <= mid; i++) {
temp[currentIndex++] = a[i];
}
}
if (j <= hight) {
for (; j <= hight; j++) {
temp[currentIndex++] = a[j];
}
}
// 拷贝
for (int m = 0; m < temp.length; m++) {
a[low + m] = temp[m];
}
}
private static void printData(int[] a) {
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < a.length; i++) {
stringBuffer.append(a[i] + " ");
}
Log.d("zpb", "value:" + stringBuffer.toString());
}
}