首页 > 编程语言 > 详细

归并排序(java)

时间:2014-10-30 11:10:27      阅读:161      评论:0      收藏:0      [点我收藏+]
package com.abin.lee.algorithm.merge;
import java.util.Arrays;
/**
 * 归并排序
 */
public class MergeSort {
public static void main(String[] args) {
int[] input = {2,7,3,9,1,6,0,5,4,8};
MergeSort.sort(input, 0, input.length-1);
System.out.println("input="+Arrays.toString(input));
}
//首先分而自治
/** 
     * 归并排序 
     * 简介:将两个(或两个以上)有序表合并成一个新的有序表 即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列 
     * 时间复杂度为O(nlogn) 
     * 稳定排序方式 
     * @param nums 待排序数组 
     * @return 输出有序数组 
     */  
public static int[] sort(int[] input,int low,int high){
int middle = (low+high)/2;
if(low<high){
//左边
sort(input,low,middle);
//右边
sort(input,middle+1,high);
//左右归并
merge(input,low,high,middle);
}
return input;
}
public static void merge(int[] input,int low,int high,int middle){
int[] temp = new int[high-low+1];
int i = low;//左指针
int j = middle+1;//右指针
int k=0;
// 把较小的数先移到新数组中  
while(i<=middle&&j<=high){
if(input[i]<input[j]){
temp[k++] = input[i++];
}else{
temp[k++] = input[j++];
}
}
// 把左边剩余的数移入数组  
while(i<=middle){
temp[k++] = input[i++];
}
// 把右边边剩余的数移入数组  
while(j<=high){
temp[k++] = input[j++];
}
// 把新数组中的数覆盖input数组  
for(int m=0;m<temp.length;m++){
input[m+low] = temp[m];
}
}
}

归并排序(java)

原文:http://www.blogjava.net/stevenjohn/archive/2014/10/17/418861.html

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