/*
归并排序
*/
public class Sort {
//将两个有序数组合并成一个有序数组
public int[] guibing(int left[], int right[]) {
int temp[] = new int[left.length + right.length];
int t = 0;
int i = 0;
int j = 0;
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
temp[t] = left[i];
i++;
} else {
temp[t] = right[j];
j++;
}
t++;
}
while (i >= left.length && t < temp.length) {
temp[t] = right[j];
j++;
t++;
}
while (j >= right.length && t < temp.length) {
temp[t] = left[i];
i++;
t++;
}
return temp;
}
//归并排序
//给一个数组返回一个有序数组
public int[] sort(int arr[]) {
int[][] b = new int[arr.length][]; //利用二维数组拆分一维数组
int i = 0;
for (i = 0; i < arr.length; i++) {
b[i] = new int[]{arr[i]};
}
//调用归并
int recive[] = b[0];
for (int j = 1; j < arr.length; j++) {
recive = guibing(recive, b[j]); //循环接收
}
return recive;
}
public static void main(String[] args) {
int arr[] = {23, 56, 80, 72, 86, 96, 97};
Sort sort = new Sort();
int[] temp = sort.sort(arr);
for (int i = 0; i < temp.length; i++) {
System.out.print(temp[i] + ",");
}
}
}