【发布时间】:2020-08-16 21:50:40
【问题描述】:
我已经使用分治法实现了一种合并排序算法,其中一个数组被分成两个子数组。
在我的代码中,我重新使用了插入排序算法对合并排序中的子数组进行排序。这是正确的方法还是我必须使用不同的排序方法对合并排序中的子数组进行排序?
至于对归并排序算法的理解,一切都已经很清楚了,但是说到归并排序的实现,如何不使用递归策略将一个数组划分为n-sub数组呢?
是递归还是非递归有效的方式来实现归并排序?
以下是我在 github 中的代码 sn-p: https://github.com/vamsikankipati/algorithms-in-java/blob/master/src/com/algorithms/sort/MergeSort.java
我从实现的角度理解我的代码是错误的,因为我将数组分成了两个子数组而不是 n-sub 数组。
从算法实现角度清楚地理解归并排序所需的任何帮助。
代码如下:
package com.algorithms.sort;
public class MergeSort {
public static int[] increasing(int[] arr) {
int[] result = new int[arr.length];
int q = arr.length / 2;
System.out.println("q: " + q);
int[] left = new int[q];
int[] right = new int[q];
for (int i = 0; i < q; i++) {
left[i] = arr[i];
}
int k = 0;
for (int j = q; j < arr.length; j++) {
right[k] = arr[j];
k += 1;
}
left = InsertionSort.increasing(left);
right = InsertionSort.increasing(right);
// Printing
for (int e : left) {
System.out.print(e);
}
System.out.println("\n");
for (int e : right) {
System.out.print(e);
}
System.out.println("\n");
int i = 0;
int j = 0;
int s = 0;
while ((i < left.length) && (j < right.length)) {
if (left[i] <= right[j]) {
result[s] = left[i];
i++;
} else {
result[s] = right[j];
j++;
}
s++;
}
while (i < left.length) {
result[s] = left[i];
i++;
s++;
}
while (j < right.length) {
result[s] = right[j];
j++;
s++;
}
return result;
}
/**
* Main method to test an example integer array
*/
public static void main(String[] args) {
int[] ar = { 18, 12, 11, 6, 55, 100 };
int[] res = increasing(ar);
for (int a : res) {
System.out.print(a + " ");
}
}
}
【问题讨论】:
-
this 问题有帮助吗?
-
部分是的,但是我们如何在不使用递归的情况下实现归并排序呢?根据您的链接,它说 O(n lg n) 是递归和非递归合并排序的时间复杂度。
-
这可以通过简单的谷歌搜索轻松获得。不是吗?
-
我建议您搜索如何以非递归方式编写递归,反之亦然。这会给你的想法。
标签: java algorithm sorting recursion mergesort