ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

归并排序(二)

2021-01-04 02:32:43  阅读:179  来源: 互联网

标签:归并 int list head middle tempList 排序 rear


 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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有