数据结构与算法-归并排序
1.递归的概念
1.首先写一个小方法,对2个已经排好顺序的数组进行归并排序
代码如下:
1 public static void MergeSortPart1() 2 { 3 int[] arr = { 1, 4, 7,8, 3, 6, 9 }; 4 var tempArr = new int[arr.Length]; 5 var tempIndex = 0; 6 7 int leftIndex = 0; 8 9 int mid = 3; 10 11 int rightIndex = mid + 1; 12 13 while (leftIndex <= mid && rightIndex< arr.Length) 14 { 15 if (arr[leftIndex] <= arr[rightIndex]) 16 { 17 tempArr[tempIndex] = arr[leftIndex]; 18 leftIndex++; 19 tempIndex++; 20 } 21 else 22 { 23 tempArr[tempIndex] = arr[rightIndex]; 24 rightIndex++; 25 tempIndex++; 26 } 27 } 28 29 if (leftIndex<=mid) 30 { 31 while (leftIndex <= mid) 32 { 33 tempArr[tempIndex] = arr[leftIndex]; 34 tempIndex++; 35 leftIndex++; 36 } 37 } 38 39 if (rightIndex<arr.Length) 40 { 41 while (rightIndex <arr.Length) 42 { 43 tempArr[tempIndex] = arr[rightIndex]; 44 rightIndex++; 45 tempIndex++; 46 47 } 48 } 49 50 //PrintArr(tempArr); 51 52 53 }
2.改进上面的方法,参数是传入的数组,leftB的位置,mid的位置,rightB 的位置,就是对一个传入数组的指定边界的元素序列进行排序
1 public static void MergeSortPart2(int[] arr, int leftB, int minPtr, int rightB) 2 { 3 4 var tempArr = new int[rightB - leftB + 1]; 5 var tempIndex = 0; 6 7 int leftIndex = leftB; 8 9 int mid = minPtr; 10 11 int rightIndex = mid + 1; 12 13 while (leftIndex <= mid && rightIndex <= rightB) 14 { 15 if (arr[leftIndex] <= arr[rightIndex]) 16 { 17 tempArr[tempIndex] = arr[leftIndex]; 18 leftIndex++; 19 tempIndex++; 20 } 21 else 22 { 23 tempArr[tempIndex] = arr[rightIndex]; 24 rightIndex++; 25 tempIndex++; 26 } 27 } 28 29 if (leftIndex <= mid) 30 { 31 while (leftIndex <= mid) 32 { 33 tempArr[tempIndex] = arr[leftIndex]; 34 tempIndex++; 35 leftIndex++; 36 } 37 } 38 39 if (rightIndex <= rightB) 40 { 41 while (rightIndex <= rightB) 42 { 43 tempArr[tempIndex] = arr[rightIndex]; 44 rightIndex++; 45 tempIndex++; 46 47 } 48 } 49 50 //更新原数组元素 51 for (int i = 0; i < tempArr.Length; i++) 52 { 53 arr[leftB+i] = tempArr[i]; 54 } 55 56 //Console.WriteLine($"当前排序:leftB:{leftB} ,rightB:{rightB},min:{minPtr}"); 57 58 //PrintArr(tempArr); 59 }
3.编写递归方法
1 public static void MergeSortPart3(int[] arr ,int leftB,int rightB) 2 { 3 4 if (leftB==rightB) 5 { 6 return; 7 } 8 9 //分成2半 10 var mid = (leftB + rightB) / 2; 11 12 //左边排序 13 MergeSortPart3(arr, leftB, mid); 14 15 //右边排序 16 MergeSortPart3(arr, mid+1 , rightB); 17 18 //merge排序 19 MergeSortPart2(arr, leftB, mid, rightB); 20 21 }
4.调用
1 public static void MergeSort(int[] arr) 2 { 3 MergeSortPart3(arr, 0, arr.Length-1); 4 5 }