【JAVA】JAVA实现归并排序

import java.util.*;


public class Test {

  public static void main(String[] args){
        int[] arr = new int[]{2,1,6,4,7,9};
        resunion(arr,0,5);
        System.out.println(Arrays.toString(arr));
  }


    public  static void  resunion(int[] nums, int left , int right){
      if(left >= right - 1 ){
          if( nums[left] > nums[right]){
              int temp = nums[left];
              nums[left] = nums[right];
              nums[right] = temp;
          }

          return ;
      }

      int mid = (left + right) / 2;


      resunion(nums,left,mid);
      resunion(nums,mid + 1, right);

      int[] tempnums = new int[nums.length + 1 ];

        int p1 = left, p2 = mid + 1,k = left;

        while(p1 <= mid || p2 <= right){
            if(p2 > right || (p1 <= mid && nums[p1] <= nums[p2])){
                tempnums[k++] = nums[p1++];
            }else{
                tempnums[k++] = nums[p2++];
            }
        }

        for(int i = left ; i <= right; i++){
            nums[i] = tempnums[i];
        }


    }

}

你可能感兴趣的:(JAVA)