归并排序
来源:互联网 发布:nginx域名重定向404 编辑:程序博客网 时间:2024/06/06 02:50
刚刚写了一篇关于快速排序的,趁热打铁索性写一个归并排序吧。其实归并排序和快速排序类似,先写递归式,再写合并方法。都是用了这种从外往里写的写法。
1 递推式
public static void mergeSort(int[] a,int left,int right){
int middle = (left + right)/2;
if(left<right){
mergeSort(a,left,middle);
mergeSort(a,middle+1,right);
merge(a,left,middle,right);
}
}
2 public static void merge(int[] a,int left,int middle,int right){
int[] temp = new int[right-left+1];
int i = left;
int j = middle +1;
int k = 0;
while(i<=middle&&j<=right){
if(a[i]<a[j]){
temp[k++] = a[i];
i++;
}else{
temp[k++] = a[j];
j++;
}
}
while(i<=middle){
temp[k++] = a[i++];
}
while(j<=right){
temp[k++] = a[j++];
}
for(int m = 0;m<temp.length;m++){
a[m] = temp[m];
}
}
主要是理解了思想再写,不然会显得很难。其实快速排序和归并排序都是很简单的。- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- c++经典类库
- Java中break和continue的区别与作用
- if 语句
- 套接字
- 解决item不能够在ActionBar上显示,只显示在overflow的问题
- 归并排序
- PF_RING DNA/Libzero vs Intel DPDK
- 单向循环链表,头插,尾插,中间插入,删除等功能
- 5-8 构造一个银行账户类
- Sublime Text使用教程
- 通过HTTP RESTful API 操作elasticsearch搜索数据
- Java多线程学习笔记(一)
- spring学习总结(十):基于 XML 的配置AOP
- 一些stl格式的点云的显示结果