19、排序算法-归并排序
来源:https://www.bilibili.com/video/BV1B4411H76f?p=60
一、思路
归并排序:经典的分治策略解决排序问题
例如:[8,4,,7,1,3,6,2] 从小到大
分:
1、[8,4,5,7] [1,3,6,2]
2、[8,4] [5,7] [1,3] [6,2]
3、[8] [4] [5] [7] [1] [3] [6] [2]
治:
1、[4,8] [5,7] [1,3] [2,6]
2、 [4,5,7,8] [1,2,3,6]
3、[1,2,3,4,5,6,7,8]
治的过程(以最后一次治为例 [4,5,7,8] [1,2,3,6]):
两个数组分别给定指针,i=0,j=0, 比较,取小的值,[1] ,对应的j++
i=0,j=1,比较,得到[1,2],j++
i=0,j=2,比较,得到[1,2,3],j++
i=0,j=3,比较,得到[1,2,3,4],i++
i=1,j=3,比较,得到[1,2,3,4,5],i++
i=2,j=3,比较,得到[1,2,3,4,5,6],j++
j已经无法继续后移,取出前面i对应数组剩余的数据,添加到后面,完成
二、实现
1 //归并排序 2 public class MergeSort { 3 public static void main(String[] args) { 4 int[] arr = {8,4,5,7,1,3,6,2}; 5 System.out.println(Arrays.toString(arr)); 6 int left = 0; 7 int right = arr.length - 1; 8 int[] temp = new int[arr.length];//存放取出来的数据 9 10 mergeSort(arr,left,right,temp); 11 System.out.println(Arrays.toString(arr)); 12 } 13 14 public static void mergeSort(int[] arr, int left, int right, int[] temp){ 15 if(left < right){ 16 int mid = (left + right)/2; 17 mergeSort(arr,left,mid,temp); 18 mergeSort(arr,mid+1,right,temp); 19 20 merge(arr,left,mid,right,temp); 21 } 22 23 } 24 25 //治 26 public static void merge(int[] arr, int left, int mid, int right, int[] temp){ 27 int i = left; 28 int j = mid + 1; 29 int t = 0;//temp的下标 30 31 //按照顺序比较 32 while (i <= mid && j <= right){ 33 if(arr[i] <= arr[j]){ 34 temp[t] = arr[i]; 35 i += 1; 36 t += 1; 37 }else { 38 temp[t] = arr[j]; 39 j += 1; 40 t += 1; 41 } 42 } 43 //比较完了,看剩没剩下 44 while (i <= mid){ 45 temp[t] = arr[i]; 46 i += 1; 47 t += 1; 48 } 49 while (j <= right){ 50 temp[t] = arr[j]; 51 j += 1; 52 t += 1; 53 } 54 55 //将暂存的数据传给原来的arr 56 t = 0; 57 int tempLeft = left; 58 while (tempLeft <= right){ 59 arr[tempLeft] = temp[t]; 60 t += 1; 61 tempLeft += 1; 62 } 63 64 65 } 66 }
结果
[8, 4, 5, 7, 1, 3, 6, 2]
[1, 2, 3, 4, 5, 6, 7, 8]