英文:
Specific problem with Implementation of a Merge Sort Algorithm
问题
/**
* 归并排序算法
* @param array 要排序的数组
* @param i - 开始排序的位置
* @param j - 结束排序的位置
*/
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 |
显然,这并不是按字母顺序排列的,只是不能弄清楚为什么。
英文:
Java
I am attempting to write a merge sort algorithm in order to sort a list of custom objects into alphabetical order, I have now been looking at my code and the pseudocode for a couple hours and have yet to figure out why it isn't working,
Perhaps some fresh eyes could help,
My code is as follows...
/**
* 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.compareTo(array[q]) == 1){
temp[r++] = array
;
}else{
temp[r++] = array[q++];
}
}
while (p <= m){
temp[r++] = array
;
}
while (q <= j){
temp[r++] = array[q++];
}
System.arraycopy(temp,0,array,0,temp.length);
}
When testing on cases of "a,b,c,d,e,h,y,z", the output is as follows...
a |
b |
d |
e |
h |
c |
y |
z |
Evidently this is not in alphabetical order, just can't figure out why
答案1
得分: 0
从您在评论中发布的伪代码中,我可以告诉您,您没有实现给定的伪代码。
Merge(A[i...j], m) 函数具有参数 m,即中间值,数组 A 以及 参数 i 和 j,用于定义在该数组中进行合并的范围。在我看来,伪代码并不准确,质量不佳。
参数 i 和 j 被用于初始化 p 和 r。在您当前的实现中,您将两者都初始化为 0
,这与伪代码不符。
您的 merge
方法需要这两个参数 i
和 j
来定义合并的范围。
英文:
Looking at the pseudocode you've posted in a comment I can tell you that you haven't implemented that given pseudocode.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论