合并排序算法java实现
时间: 2023-11-17 19:04:25 浏览: 97
好的,合并排序算法的Java实现如下:
```
public class MergeSort {
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);
}
}
private static void merge(int[] arr, int left, int mid, int right) {
int[] tempArr = new int[right - left + 1];
int i = left, j = mid + 1, curr = 0;
while (i <= mid && j <= right) {
if (arr[i] < arr[j]) {
tempArr[curr++] = arr[i++];
} else {
tempArr[curr++] = arr[j++];
}
}
while (i <= mid) {
tempArr[curr++] = arr[i++];
}
while (j <= right) {
tempArr[curr++] = arr[j++];
}
for (int k = 0; k < tempArr.length; k++) {
arr[left + k] = tempArr[k];
}
}
}
```
该算法的时间复杂度为O(nlogn),可以对任意长度的数组进行排序。
阅读全文