归并排序

 

 

import java.util.Arrays;

public class Main {
public static void main(String[] args) {
int[] a = {2, 3, 5, 1, 4, 7, 8, 5, 7, 9, 0, -3};
GuiBing(a, 0, a.length - 1);
System.out.println(Arrays.toString(a));
}
public static void merge(int[] a, int left, int mid, int right) {
int i = left;
int j = mid + 1;
int k = 0;
int[] temp = new int[right - left + 1];
while (i <= mid && j <= right) {
if (a[i] < a[j]) {
temp[k++] = a[i++];
} else {
temp[k++] = a[j++];
}
}
while (i <= mid) {
temp[k++] = a[i++];
}
while (j <= right) {
temp[k++] = a[j++];
}
for (int m = 0; m < temp.length; m++) {
a[left + m] = temp[m];
}
}
public static void GuiBing(int[] a, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
GuiBing(a, left, mid);
GuiBing(a, mid + 1, right);
merge(a, left, mid, right);
}
}
}
posted @ 2024-02-19 20:14  赵千万  阅读(2)  评论(0编辑  收藏  举报