首页 > 编程语言 > 详细

2路归并排序

时间:2015-03-27 22:05:16      阅读:256      评论:0      收藏:0      [点我收藏+]

import java.util.Arrays;


public class Merge_sort {
public static void main(String[] args){
int[] nums={ 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 };
sort(nums,0,nums.length-1);
System.out.println(Arrays.toString(nums));
}

public static int[] sort(int[] num,int low,int high){
int mid=(low+high)/2;
if(low<high){ 
//左排序
sort(num,low,mid);
//右排序
sort(num,mid+1,high);
Merge(num, low,mid, high);
}
return num;
}

public static void Merge(int[] num,int low,int mid,int high){

int[] temp=new int[high-low+1];
int i=low;
int j=mid+1;
int k=0;
while(i<=mid&&j<=high){
if(num[i]<=num[j]){
temp[k]=num[i];
i++;
}else{
temp[k]=num[j];
j++;
}
k++;
}
while(i<=mid){
temp[k]=num[i];
k++;
i++;
}
while(j<=high){
temp[k]=num[j];
k++;
j++;
}

for(int m=0;m<temp.length;m++){
num[low++]=temp[m];

}
}

}

2路归并排序

原文:http://www.cnblogs.com/catWang/p/4372861.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!