归并排序java代码
时间: 2023-11-12 08:57:05 浏览: 89
java代码-使用java解决java排序之-归并排序的问题的源代码
归并排序(Merge Sort)是一种稳定的排序算法,采用分治法(Divide and Conquer)的思想,将待排序的序列分成若干个子序列,每个子序列都是有序的,然后再将有序子序列合并为整体有序序列。
以下是归并排序的Java代码实现:
```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);
}
}
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 main(String[] args) {
int[] arr = {5, 3, 8, 6, 4};
mergeSort(arr, 0, arr.length - 1);
for (int i : arr) {
System.out.print(i + " ");
}
}
}
```
阅读全文