提交 be196d61 编写于 作者: 漫长的~以后's avatar 漫长的~以后

1.归并算法排序

上级 54e8de14
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);
}
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.
先完成此消息的编辑!
想要评论请 注册