排序算法之归并排序
来源:互联网 发布:c语言源代码大全 编辑:程序博客网 时间:2024/06/06 03:17
归并排序的含义
归并排序的含义可以分为两个部分:先递归下去,之后再两两合并,最后就是排序好的整体序列了。
具体思路:首先将整体序列分为两部分,之后对每个部分再次进行二分,循环前述的这些操作。直到两两分组之后的结果都为一个数字,之后比较两个数字的大小进行排序。成为一个排序好的小序列,之后和相邻的小序列再次合并,直到将所有的子序列合并完成,最终成为整体有序序列。
代码实现
public class MergeSort { /** * 归并排序 * 简介:将两个(或两个以上)有序表合并成一个新的有序表 即把待排序序列分为若干个子序列, * 每个子序列是有序的。然后再把有序子序列合并为整体有序序列 * 时间复杂度为O(nlogn) * 稳定排序方式 * @param nums 待排序数组 * @return 输出有序数组 */ public static void 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); } } 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++]; } // 把新数组中的数覆盖nums数组 for (int k2 = 0; k2 < temp.length; k2++) { nums[k2 + low] = temp[k2]; } } // 归并排序的实现 public static void main(String[] args) { int[] nums = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 }; MergeSort.sort(nums, 0, nums.length-1); System.out.println(Arrays.toString(nums)); }
阅读全文
0 0
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 排序算法之归并排序
- 【BZOJ1007】【HNOI2008】水平可见直线
- 【s5p4418嵌入式学习】分步编译之module编译05
- 8章 进程控制
- 大数据排重算法-布隆算法(BloomFilter)
- 微信小程序--后端管理平台业务4--Mybatis模糊查询相关
- 排序算法之归并排序
- 数据结构-数组
- 机器学习故事汇-决策树算法
- scala实现超限学习机(ELM)手写数字分类
- Android之点击返回键退出程序
- java正则表达式匹配
- 念念不忘的高薪,就用linux学习来回响
- mybatis中的#和$的区别? 面试经常问到!!
- 1003度度熊与邪恶大魔王(完全背包)