0
点赞
收藏
分享

微信扫一扫

归并排序(Java代码实现)

小北的爹 2022-02-12 阅读 35
import java.util.Arrays;

public class Paixu {
    public static void main(String[] args) {
        int[] arr = new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1};
        int[] temp = new int[arr.length];
        Fen(arr,0,arr.length-1,temp);

        System.out.println(Arrays.toString(arr));
    }
    public static void Fen(int[] arr, int left,int right, int[] temp ){
        if(left < right){
            int mid = (left + right) /2;
            Fen(arr,left,mid,temp);
            Fen(arr,mid+1,right,temp);
            GuiBing(arr,left,mid,right,temp);
        }
    }

    public static void GuiBing(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        int t = 0;
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[t] = arr[i];
                t++;
                i++;
            } else {
                temp[t] = arr[j];
                t++;
                j++;
            }
        }
        while (i <= mid) {
            temp[t] = arr[i];
            t++;
            i++;
        }
        while (j <= right) {
            temp[t] = arr[j];
            t++;
            j++;
        }

        t = 0;
        int tempLeft = left;
        while (tempLeft <= right) {
            arr[tempLeft] = temp[t];
            t++;
            tempLeft += 1;
        }


    }

    


}


举报

相关推荐

0 条评论