归并排序

原理

  • 分治思想
  • 将数组分为每份只有1的小数组
  • 将数组合并

可以说是没有基准指标的快速排序

代码实现

  1. import java.util.Arrays;
  2. /**
  3. * @author laoduan
  4. * @create 2020-05-08-22:27
  5. */
  6. public class mergeSort {
  7. public static void main(String[] args) {
  8. int arr[] = {8,4,5,7,1,3,6,2};
  9. int temp[] = new int [arr.length];
  10. mergeSort(arr,0,arr.length-1,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. //向左递归分解
  18. mergeSort(arr,left,mid,temp);
  19. //向右递归分解
  20. mergeSort(arr,mid+1,right,temp);
  21. //合并
  22. merge(arr,left,mid,right,temp);
  23. }
  24. }
  25. /**
  26. *合并
  27. * @param arr
  28. * @param left
  29. * @param right
  30. * @param temp
  31. */
  32. public static void merge(int arr[],int left,int mid,int right,int[] temp){
  33. int i =left;
  34. int j = mid+1;
  35. int t = 0;//指向temp数组的当前索引
  36. //先把左右两边(有序)的数据按照规则填充到temp数组
  37. //直到左右两边的有序序列,有一边处理完毕为止
  38. while (i<=mid && j<=right){
  39. //如果左边有序序列的当前元素小于等于右边有序序列的当前元素
  40. //将左边当前元素拷贝到temp
  41. //t后移i后移
  42. if(arr[i]<=arr[j]){
  43. temp[t]=arr[i];
  44. t +=1;
  45. i +=1;
  46. }else {
  47. temp[t] =arr[j];
  48. t +=1;
  49. j +=1;
  50. }
  51. }
  52. while (i<=mid){
  53. temp[t] = arr[i];
  54. t+=1;
  55. i+=1;
  56. }
  57. while (j<=right){
  58. temp[t] = arr[j];
  59. t+=1;
  60. j+=1;
  61. }
  62. t = 0;
  63. int tempLeft = left;
  64. System.out.println("tempLeft= "+tempLeft+" ,right= "+right);
  65. while (tempLeft<=right)
  66. {
  67. arr[tempLeft]=temp[t];
  68. t+=1;
  69. tempLeft+=1;
  70. }
  71. }
  72. }