合并排序
来源:互联网 发布:单片机自动门源程序 编辑:程序博客网 时间:2024/06/08 16:13
所有子序列都进行两路合并,递归实现。
import java.util.Arrays;public class MergeSort { 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++]; } // 把新数组中的数覆盖部分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
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 合并排序
- 输入法技术指标拆解
- 如何转载CSDN博客
- 基于UDP的P2P聊天工具 0.3——消息队列和重传
- 广播
- git+maven自动化部署tomcat java项目
- 合并排序
- 深入浅出 Python Generators
- hdu 2159 FATE(二维背包+完全背包)
- Holiday's Accommodatio UVA
- Python 起步-list的小总结
- 初识maven
- 171105-初步自学内联函数和重载函数【连续第十三天】
- 设计模式解决的问题
- MATLAB散点图、表面图、等高线图绘制命令