归并排序(二)
作者:互联网
1 public class guiBing2 { 2 public static void mergeSort(int[] list,int[] tempList,int head,int rear){ 3 if(head < rear){ 4 //取分割位置 5 int middle = (head + rear) / 2; 6 //递归划分列表的左序列 7 mergeSort(list,tempList,head,middle); 8 //递归划分列表的右序列 9 mergeSort(list,tempList,middle + 1,rear); 10 //列表合并 11 merge(list,tempList,head,middle + 1,rear); 12 } 13 } 14 /** 15 * merge 16 * 合并俩表 17 */ 18 public static void merge(int[] list,int[] tempList,int head,int middle,int rear){ 19 //左指针尾 20 int headEnd = middle - 1; 21 //右指针头 22 int rearStart = middle; 23 //临时列表的下标 24 int tempIndex = head; 25 //列表合并后的长度 26 int tempLength = rear - head + 1; 27 28 //先循环俩个区间段都没有结束的情况 29 while ((headEnd >= head) && (rearStart <= rear)){ 30 //如果发现右序列大,则将此树放入临时列表 31 if(list[head] < list[rearStart]){ 32 tempList[tempIndex++] = list[head++]; 33 } else { 34 tempList[tempIndex++] = list[rearStart++]; 35 } 36 } 37 38 //判断左序列是否结束 39 while (head <= headEnd){ 40 tempList[tempIndex++] = list[head++]; 41 } 42 //判断右序列是否结束 43 while (rearStart <= rear){ 44 tempList[tempIndex++] = list[rearStart++]; 45 } 46 47 //交换数据 48 for (int i = 0; i < tempLength; i++) { 49 list[rear] = tempList[rear]; 50 rear--; 51 } 52 } 53 }
标签:归并,int,list,head,middle,tempList,排序,rear 来源: https://www.cnblogs.com/peanut-zh/p/14227684.html