提交 742cc17b 编写于 作者: 幻灰龙's avatar 幻灰龙

Merge branch 'master' into 'master'

Java 归并算法

See merge request !6
class Solution {
public static void mergeSort(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int[] helper = new int[nums.length];
mergeSort(nums, helper, 0, nums.length - 1);
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
}
private static void mergeSort(int[] nums, int[] helper, int low, int high) {
if (low < high) {
int middle = low + (high - low) / 2;
mergeSort(nums, helper, low, middle);
mergeSort(nums, helper, middle + 1, high);
merge(nums, helper, low, middle, high);
}
}
private static void merge(int[] nums, int[] helper, int low, int middle, int high) {
for (int i = low; i <= high; i++) {
helper[i] = nums[i];
}
int left = low;
int right = middle + 1;
int curr = low;
while (left <= middle && right <= high) {
if (helper[left] <= helper[right]) {
nums[curr++] = helper[left++];
} else {
nums[curr++] = helper[right++];
}
}
int remain = middle - left;
for (int i = 0; i <= remain; i++) {
nums[curr + i] = helper[left + i];
}
}
}
\ No newline at end of file
# 归并排序
你需要用归并排序算法,对数组进行排序,并输出按照升序排序的字符数字串
归并排序算法的基本思想是将两个(或两个以上)有序表合并成一个新的有序表,
即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
## 输入描述
你需要对输入的数组根据归并排序算法升序排序
## 输出描述
输出按照升序排序的数组
## 输入样例
输入nums数组为:
1. int[] nums = new int{}[1,2,4,3,5,6,7,8];
2. int[] nums = new int{}[1,5,6,10,12,15,2,4];
3. int[] nums = new int{}[1,4,90,12,14,19,3,4];
## 输出样例
1. 1,2,3,4,5,6,7,8
2. 1,2,4,5,6,10,12,15
3. 1,3,4,4,12,14,19,90
## 提示
\ No newline at end of file
int[] nums = new int{}[1,2,4,3,5,6,7,8];
\ No newline at end of file
1
2
3
4
5
6
7
8
\ No newline at end of file
int[] nums = new int{}[1,5,6,10,12,15,2,4];
\ No newline at end of file
1
2
4
5
6
10
12
15
\ No newline at end of file
int[] nums = new int{}[1,4,90,12,14,19,3,4];
\ No newline at end of file
1
3
4
4
12
14
19
90
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册