归并排序--java实现

来源:互联网 发布:淘宝机票改签流程 编辑:程序博客网 时间:2024/05/22 12:18

归并排序--java实现

                                                邝倍靖

package sort;

import java.util.Arrays;

public class MergeSort {
 public static void main(String[] args) {
  int[] nums = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 }; 
//  int[] nums = { 2, 7, 4 }; 
  MergeSort.sort(nums, 0, nums.length-1); 
  System.out.println(Arrays.toString(nums));
 }
 
 /**
  * @对数组进行归并排序
  * @date 2016-10-13
  * @author kbj
  * @param nums
  * @param low
  * @param high
  * @return
  */
 public static int[] sort(int[] nums, int low, int high){
  int mid = (low+high)/2;
  if(low<high){
   sort(nums,low,mid); //左边
   sort(nums,mid+1, high); //右边
   merge(nums, low, mid, high);//low到high区间数字进行排序
  }
  return nums;
 }
 
 
 private static void merge(int[] nums, int low, int mid, int high) {
  // TODO Auto-generated method stub
  int temp[] = new int[high - low +1];
  int i = low;
  int j = mid+1;
  int k = 0;
  while(i<= mid && j<=high){
   if(nums[i] < nums[j]){
    temp[k++] = nums[i++];
   }else{
    temp[k++] = nums[j++];
   }
  }
  
  //加上左边的剩下数字
  while(i<=mid){
   temp[k++] = nums[i++];
  }
  
  //加上右边的是剩下数字,两边只可能执行一遍
  while(j<=high){
   temp[k++] = nums[j++];
  }
  
  //把临时拍好序的数字覆盖到nums对应的数字区
  for(int t = 0; t<temp.length; t++){
   nums[low+t] = temp[t];
  }
 }
}

   
0 0
原创粉丝点击