归并排序
一、问题描述
对数组进行排序
二、方法
- 每次对两个小数组进行排序
- 将整个大数组一直切分成小数组
三、思想
分治。
四、code
1 package algorithm; 2 3 /** 4 * Created by adrian.wu on 2019/2/14. 5 */ 6 public class MergeSort { 7 public void merge(int[] nums, int s, int m, int e) { 8 if (s >= e) return; 9 10 //new sorted nums 11 int[] nsn = new int[e - s + 1]; 12 13 //as is the start position of s, bs is the start position of b, c is count 14 int c = 0, as = s, bs = m + 1; 15 while (as <= m && bs <= e) { 16 if (nums[as] <= nums[bs]) { 17 nsn[c++] = nums[as++]; 18 } else { 19 nsn[c++] = nums[bs++]; 20 } 21 } 22 23 while (as <= m) nsn[c++] = nums[as++]; 24 while (bs <= e) nsn[c++] = nums[bs++]; 25 26 for (int i = s; i <= e; i++) { 27 nums[i] = nsn[i - s]; 28 } 29 } 30 31 public void mergeSort(int[] nums, int s, int e) { 32 //next mid 33 if (s >= e) return; 34 int m = (e + s) / 2; 35 mergeSort(nums, s, m); 36 mergeSort(nums, m + 1, e); 37 merge(nums, s, m, e); 38 } 39 }
谢谢!