java - 实现合并排序算法的具体问题
问题描述
爪哇
我正在尝试编写一个合并排序算法,以便按字母顺序对自定义对象列表进行排序,我现在已经查看了我的代码和伪代码几个小时,还没有弄清楚为什么它不起作用,
也许一些新鲜的眼睛可以帮助,
我的代码如下...
/**
* Merge Sort Algorithm
* @param array array to sort
* @param i - point to start sorting at
* @param j - point to end sorting at
*/
public void MergeSort(Movie[] array, int i, int j) {
if(i < j){
int m = (i+j)/2;
MergeSort(array, i, m);
MergeSort(array, m+1, j);
merge(array,m);
}
}
void merge(Movie[] array, int m){
int p = 0;
int q = m+1;
int r = 0;
int j = array.length-1;
Movie[] temp = new Movie[array.length];
while(p <= m && q <= j){
if(array[p].compareTo(array[q]) == 1){
temp[r++] = array[p++];
}else{
temp[r++] = array[q++];
}
}
while (p <= m){
temp[r++] = array[p++];
}
while (q <= j){
temp[r++] = array[q++];
}
System.arraycopy(temp,0,array,0,temp.length);
}
在测试“a,b,c,d,e,h,y,z”的情况时,输出如下...
a |
b |
d |
e |
h |
c |
y |
z |
显然这不是按字母顺序排列的,只是无法弄清楚为什么
解决方案
查看您在评论中发布的伪代码,我可以告诉您,您还没有实现给定的伪代码。
The Merge(A[i...j], m) function has the parameters m, which is the mid, the array A and the parameters i and j to define the bounds for the merging in that array. In my opinion the pseudocode is just not precise and bad.
The parameters i and j are used to initialize p and r. In your current implementation you are initializing both with 0
, which is not what the pseudocode does.
Your method merge
needs those two parameters i
and j
to define the bounds for the merging.
推荐阅读
- javascript - 在变量中获取http请求的响应
- azure-devops - 如何为每个部署代理设置发布变量范围
- swift - 如何在 macOS 钥匙串中存储对称加密密钥?
- python - 如何优化使用大量插值的python中的慢双积分?也许使用 Numba?
- azure - Azure Lucene 模糊搜索
- algorithm - Kotlin 地图值转换 - 计算列表内的总和并返回地图
- android - 如何打开用户在android中的活动
- javascript - `super()` 是否应该为函数返回 `this`?
- c - C - 如何将数字移动到矩阵中的不同位置
- python - 使用拆分标签解析 xml / xpath