归并排序
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);
}
}
}
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);
}
}
}
本文来自博客园,作者:赵千万,转载请注明原文链接:https://www.cnblogs.com/zhaoqianwan/p/17899841.html
千万千万赵千万