JAVA归并排序代码
时间: 2024-05-07 09:13:56 浏览: 94
JAVA归并排序的代码如下:
```
public class MergeSort {
public static void main(String[] args) {
int[] arr = { 38, 27, 43, 3, 9, 82, 10 };
System.out.println("排序前:");
printArr(arr);
mergeSort(arr, 0, arr.length - 1);
System.out.println("排序后:");
printArr(arr);
}
public static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
public static void merge(int[] arr, int left, int mid, int right) {
int[] temp = new int[right - left + 1];
int i = left;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= right) {
if (arr[i] < arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (int p = 0; p < temp.length; p++) {
arr[left + p] = temp[p];
}
}
public static void printArr(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
}
```
归并排序是一种典型的分治算法。它将待排序的元素分为两个大小大致相等的子集合,然后递归地排序两个子集合,最后将已经排好序的子集合合并成为最终的排好序的序列。
阅读全文