归并排序
来源:互联网 发布:阿里云余额如何提现 编辑:程序博客网 时间:2024/06/05 07:19
时间复杂度归并排序的复杂度为 O(n log n);最坏情况、最好情况和平均情况都是一样的。
值得注意的是归并排序是稳定的,稳定性指:假定在待排序的记录序列中,存在多个具有相同的关键字的记录,若经过排序,这些记录的相对次序保持不变,即在原序列中,ri=rj,且ri在rj之前,而在排序后的序列中,ri仍在rj之前,则称这种排序算法是稳定的;否则称为不稳定的。通俗地讲就是能保证排序前2个相等的数其在序列的前后位置顺序和排序后它们两个的前后位置顺序相同。在简单形式化一下,如果Ai = Aj,Ai原来在位置前,排序后Ai还是要在Aj位置前。
public class hello { public static int[] sort(int[] nums, int low, int high) { int mid = (low + high) / 2; if (low < high) { sort(nums, low, mid); sort(nums, mid + 1, high); merge(nums, low, mid, high); } return nums; } public static void merge(int[] nums, int low, int mid, int high) { int[] temp = new int[high - low + 1]; int i = low; int j = mid + 1; int k = 0; while (i <= mid && j <= high) { if (nums[i] < nums[j]) { temp[k++] = nums[i++]; } else { temp[k++] = nums[j++]; } } while (i <= mid) { temp[k++] = nums[i++]; } while (j <= high) { temp[k++] = nums[j++]; } for (int k2 = 0; k2 < temp.length; k2++) { nums[k2 + low] = temp[k2]; } } public static void main(String[] args) { int[] nums = { 2, 7, 7, 4, 5, 6, 9, 5, 4 }; hello.sort(nums, 0, nums.length-1); for(int i=0;i<nums.length;i++) System.out.println(nums[i]); } }
归并排序和堆排序、快速排序的比较
若从空间复杂度来考虑:首选堆排序,其次是快速排序,最后是归并排序。
若从稳定性来考虑,应选取归并排序,因为堆排序和快速排序都是不稳定的。
若从平均情况下的排序速度考虑,应该选择快速排序
阅读全文
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- c++归并排序
- 点宏染整厂ERP生产管理系统介绍
- df和du显示的磁盘空间使用情况不一致的原因及处理
- 51keil与proteus联调,实现在线仿真
- 【网络流之最大流算法模板】HDUOJ 3549 Flow Problem
- 归并排序
- 设计模式之多例模式
- 自己配置的谷歌浏览器插件
- 设计编写用例注意事项
- Visual Studio C++/C 教你四步安装graphics图形库
- [原创] Nagios install Plugin check_iostat
- React Native 项目 常用 第三方组件 汇总(一)
- BurpSuite中的安全测试插件推荐
- 使用ping简单检测网络故障