我一直在尝试进行合并排序,将字符串数组和int数组排序在一起。 int [0]指向word [0]所以当word [0]转换为word [2]时,int [0]也应该转换为int [2]。但是,我的输出是不同的: A B C D 4 3 1 3。 我做错了什么?
public static void main(String[] args) {
String[] word = {"c", "b", "d", "a"};
int[] lineNumber = {1, 2, 3, 4};
mergeSort(word, lineNumber, 0, word.length-1);
for(int i = 0; i< word.length; i++) {
System.out.print(word[i] + " ");
}
System.out.println();
for(int i =0; i < word.length; i++)
System.out.print(lineNumber[i] + " ");
}
static void mergeSort(String[] word, int[] lineNumber, int p, int r) {
int q;
if(p < r) {
q = (p+r)/2;
mergeSort(word, lineNumber, p, q);
mergeSort(word, lineNumber, q+1, r);
merge(word, lineNumber, p, q, r);
}
}
static void merge(String[] word, int[] lineNumber, int p, int q, int r) {
int n1 = q-p+1;
int n2 = r-q;
String[] lWord = new String[n1];
String[] rWord = new String[n2];
int[] lLineNum = new int[n1];
int[] rLineNum = new int[n2];
int i, j, k;
for(i=0; i<n1; i++) {
lWord[i] = word[p+i];
lLineNum[i] = lineNumber[p+i];
}
for(j=0; j<n2; j++) {
rWord[j] = word[q+j+1];
rLineNum[j] = lineNumber[q+j+1];
}
i = 0; j = 0;
for(k=p; k<=r; k++) {
if(i<n1 && j<n2) {
if(lWord[i].compareTo(rWord[j]) < 0) {
word[k] = lWord[i];
lineNumber[k] = lLineNum[i];
i++;
}else
word[k] = rWord[j];
lineNumber[k] = rLineNum[j];
j++;
}
else if(i<n1) {
word[k] = lWord[i];
lineNumber[k] = lLineNum[i];
i++;
}else if(j<n2){
word[k] = rWord[j];
lineNumber[k] = rLineNum[j];
j++;
}
}
}
答案 0 :(得分:0)
问题出在merge
。它应该是这样的:
static void merge(String[] word, int[] lineNumber, int p, int q, int r) {
int n1 = q-p+1;
int n2 = r-q;
String[] lWord = new String[n1];
String[] rWord = new String[n2];
int[] lLineNum = new int[n1];
int[] rLineNum = new int[n2];
int i, j, k;
for(i=0; i<n1; i++) {
lWord[i] = word[p+i];
lLineNum[i] = lineNumber[p+i];
}
for(j=0; j<n2; j++) {
rWord[j] = word[q+j+1];
rLineNum[j] = lineNumber[q+j+1];
}
i = 0; j = 0;
for(k=p; k<=r; k++) {
if(i<n1 && j<n2) {
if(lWord[i].compareTo(rWord[j]) < 0) {
word[k] = lWord[i];
lineNumber[k] = lLineNum[i];
i++;
}else {
word[k] = rWord[j];
lineNumber[k] = rLineNum[j];
j++;
}
} else if(i<n1) {
word[k] = lWord[i];
lineNumber[k] = lLineNum[i];
i++;
} else if(j<n2){
word[k] = rWord[j];
lineNumber[k] = rLineNum[j];
j++;
}
}
}
问题在于if-else。它们在代码中的结构不正确,看起来非常像(在修复缩进后):
if(i<n1 && j<n2) {
if(lWord[i].compareTo(rWord[j]) < 0) {
word[k] = lWord[i];
lineNumber[k] = lLineNum[i];
i++;
}else // HERE next 3 lines should be in a {} block
word[k] = rWord[j];
lineNumber[k] = rLineNum[j];
j++;
}
else if(i<n1) {
word[k] = lWord[i];
lineNumber[k] = lLineNum[i];
i++;
}else if(j<n2){
word[k] = rWord[j];
lineNumber[k] = rLineNum[j];
j++;
}
在我看来,如果不使用两个数组(int []和String []),代码会更清晰,你可以使用包含word和lineNo的类的单个数组。类似的东西:
public class WordAndPosition {
public String word;
public int lineNo;
}
WordAndPosition[]