归并排序
来源:互联网 发布:苹果6韩版支持什么网络 编辑:程序博客网 时间:2024/06/06 02:14
闲来无事写写归并排序
归并排序的思想大致如下:
首先归并排序将一个数字序列像二叉树一样进行分割及如图所示:
画第一条横线以上的部分
每次都将数字序列分割成两个序列(数字序列为奇数时左边会多一个,偶数时两部分长度相等)
及以
(low+height)/2 来分,low代表数组的下边界,height代表数组的上边界当分割到一个序列只有一个数字时,将进行归并操作
此时,有点像二叉树的后序遍历已经访问到底部了
及
它先处理的最左边的左右孩子及图中的(25,34)
处理方式如下
先比较25 和 34 发现 25小于34
就把他们两合成一个序列
而对于45 和 32 发现 32 小于 45
此时将32 和 45 合并一个序列同时交换次序;
以此类推
78 12
29 64
也是一样
这样当所有叶子节点都合并了之后
就变成了以下状态
此时我们发现4个新的小序列本身是有序的,只是整体还是无序的
接下来我们将前两个小序列合并并且调整次序,调整次序的代码如下
for(i=low;i<=height;i++){ temparray[i] = array[i]; } while(index<=middle&&index2<=height){ if(temparray[index]<temparray[index2]){ array[j++] = temparray[index++]; }else{ array[j++] = temparray[index2++]; } } while(index<=middle){ array[j++] = temparray[index++]; } while(index2<=height) { array[j++] = temparray[index2++]; }
首先我们需要一个临时的数组temparray 将真正的数组array中的前两个序列的数字复制到
temparray中 及将(25 34),(32,45)复制到temparray中 接下来我们将调整次序
然后复制到array中 具体的实现在上面有(实在没办法用语言来说出来,大家仔细想想可以看懂)
后面的两个的序列也是一样的
这样归并到最后所有的数字序列就是有序的
说一千到一万:
大家在想的时候就按二叉树的后序遍历来想就行了,其实的归并排序的就是一个自底向上的归并的过程
#include<stdio.h>void merge(int low,int height,int middle,int* array,int* temparray){ int index = low; int index2 = middle+1; int j = low; int i; for(i=low;i<=height;i++){ temparray[i] = array[i]; } while(index<=middle&&index2<=height){ if(temparray[index]<temparray[index2]){ array[j++] = temparray[index++]; }else{ array[j++] = temparray[index2++]; } } while(index<=middle){ array[j++] = temparray[index++]; } while(index2<=height) { array[j++] = temparray[index2++]; }}void sort(int low,int height,int* array,int* temparray){ if(low<height){ int middle = (low+height)/2; sort(low,middle,array,temparray); sort(middle+1,height,array,temparray); merge(low,height,middle,array,temparray); }}int main(){ int a[] = {9,8,3,4,5,3,7,5,3,5}; int b[] = {9,8,3,4,5,3,7,5,3,5}; sort(0,9,a,b); int i; for(i=0;i<=9;i++){ printf("%d",a[i]); }}
阅读全文
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- Ubuntu安装NVIDIA驱动补充
- java并发工具CountDownLatch的理解以及使用
- 2017.08.14工作日记
- 第二章 身份验证 (一) 登录、退出
- poj 3061 Subsequence(尺取)
- 归并排序
- 矩阵在游戏开发中的应用
- uC/OS-II系统学习笔记(2)——实时操作系统概念中篇
- Window Pains (POJ NO.1587 拓扑排序)
- grunt gruntfile.js详解
- Android 四大组件基础 Activity 生命周期
- 打印杨辉三角
- ThinkPHP5.0版本学习
- 北京周边-夜爬泰山