package cn.itcase;
import java.util.Arrays;
public class SortTest {
public static void main(String[] args) {
int[] arr = { 2, 5, 3, 1, 4 };
System.out.println("排序前:" + Arrays.toString(arr));
MergeSort.sort(arr);
System.out.println("排序后:" + Arrays.toString(arr));
}
/*
* 交换数组中的两个元素
*/
public static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
class MergeSort {
public static void sort(int[] data) {
int[] temp = new int[data.length];
mergeSort(data, temp, 0, data.length - 1);
}
private static void mergeSort(int[] data, int[] temp, int l, int r) {
int mid = (l + r) / 2;
if (l == r)
return;
mergeSort(data, temp, l, mid);
mergeSort(data, temp, mid + 1, r);
for (int i = l; i <= r; i++) {
temp[i] = data[i];
}
int i1 = l;
int i2 = mid + 1;
for (int cur = l; cur <= r; cur++) {
if (i1 == mid + 1)
data[cur] = temp[i2++];
else if (i2 > r)
data[cur] = temp[i1++];
else if (temp[i1] < temp[i2])
data[cur] = temp[i1++];
else
data[cur] = temp[i2++];
}
}
}
复制代码 |