算法逻辑图: 效果动图:
import org.apache.commons.lang.ArrayUtils; /** * * <pre> * 博文详细 * http://www.cnblogs.com/eniac12/p/5329396.html * 动图详细: * * http://images2015.cnblogs.com/blog/739525/201603/739525-20160328211743473-909317024.gif * * http://images2015.cnblogs.com/blog/739525/201603/739525-20160328211504519-1388466622.gif * * </pre> * * @author baoy * */ public class MergeSort { public static void main(String[] args) { int [] a = new int[]{1,2,3}; sort(a); System.out.println(ArrayUtils.toString(a)); a = new int[]{4,5,6,7}; sort(a); System.out.println(ArrayUtils.toString(a)); a = new int[]{10,11,8,9}; sort(a); System.out.println(ArrayUtils.toString(a)); } public static void sort(int []a ){ sort(a, 0, a.length-1); } public static void merge(int[] a, int left, int center, int right) { int [] temparr = new int [right - left + 1]; int i = left; int j = center + 1; int k = 0; while( i <= center && j <= right){ if( a[i] < a[j] ){ temparr[k++] = a[i++]; }else{ temparr[k++] = a[j++]; } } while (i<= center) { temparr[k++] = a[i++]; } while (j <= right) { temparr[k++] = a[j++]; } for (int l = 0; l < temparr.length; l++) { a[left++] = temparr[l]; } } public static void sort(int[] a, int left, int right) { if (left >=right) return; int center = (left + right) / 2; sort(a, left, center); sort(a, center + 1, right); merge(a, left, center, right); } }
捐助开发者
在兴趣的驱动下,写一个免费
的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。
个人主页:http://knight-black-bob.iteye.com/
谢谢您的赞助,我会做的更好!