package sort;
import java.util.Arrays;
public class GbSort {
public static void main(String[] args) {
int[] array = new int[]{9,8,7,6,5,4,3,2,1};
sort(array,0,array.length-1);
System.out.println("排序完成后的代码为:");
System.out.println(Arrays.toString(array));
}
public static int[] sort(int[] array, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
// 向左分
sort(array, left, mid);
// 向右分
sort(array, mid+1, right);
// 归并
gbSort(array, left, right, mid);
}
return array;
}
public static void gbSort(int[] array, int left, int right, int mid) {
int[] temp = new int[right-left+1];
int i = left; // 指向归并时左边的数组
int j = mid + 1; // 指向归并时右边的数组
int t = 0; // 临时数组下标
while (i <= mid && j <= right){
if (array[i] < array[j]) {
temp[t++] = array[i++];
}else {
temp[t++] = array[j++];
}
}
while (i <= mid) {
temp[t++] = array[i++];
}
while (j <= right) {
temp[t++] = array[j++];
}
t = 0;
while (left <= right) {
array[left++] = temp[t++];
}
}
}
今天写到归并开始卡壳了,菜是原罪,继续努力吧。