使用string.compareTo()插入排序 [英] Insertion Sort using string.compareTo()
问题描述
据我所知,我在这里实现了基本的插入排序。输出是相同的数组,未排序。我正确使用compareTo吗?我不确定这是一个大于或小于零的数字意味着什么。
As far as I can tell, I have implemented the basic insertion sort here. The output is the same array, unsorted. Am I making use of compareTo correctly? I am unsure what it means by being some number greater than or less than zero.
import java.util.Arrays;
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int lineNumber = 5;
int i,j;
String key;
String[] inputArray = {"E","D","C","B","A","B"};
System.out.println(Arrays.toString(inputArray));
for (j = 1; j < lineNumber; j++) {
key = inputArray[j];
i = j - 1;
while (i >= 0) {
if (key.compareTo(inputArray[i]) < 0) {
break;
}
inputArray[i + 1] = inputArray[i];
i--;
}
inputArray[i + 1] = key;
System.out.println(Arrays.toString(inputArray));
}
System.out.println(Arrays.toString(inputArray));
}
运行:
[E, D, C, B, A, B]
[E, D, C, B, A, B]
[E, D, C, B, A, B]
[E, D, C, B, A, B]
[E, D, C, B, A, B]
[E, D, C, B, A, B]
BUILD SUCCESSFUL (total time: 0 seconds)
推荐答案
正如所指出:不,你没有正确使用的compareTo()
。下面的代码按预期工作。
As pointed out: no, you are not making correct use of compareTo()
. The below code works as intended.
public static void main(String[] args) {
int i,j;
String key;
String[] inputArray = {"E","D","C","B","A","B"};
System.out.println(Arrays.toString(inputArray));
for (j = 1; j < inputArray.length; j++) { //the condition has changed
key = inputArray[j];
i = j - 1;
while (i >= 0) {
if (key.compareTo(inputArray[i]) > 0) {//here too
break;
}
inputArray[i + 1] = inputArray[i];
i--;
}
inputArray[i + 1] = key;
System.out.println(Arrays.toString(inputArray));
}
System.out.println(Arrays.toString(inputArray));
}
为什么 compareTo()
在其他答案中,它所做的事情得到了很好的解释。除此之外,我改变了直到应该运行for循环的值,它应该运行到数组的末尾(array.length),而不是直到任何其他数字。
Why the compareTo()
does what it does is explained very well in the other answers. Besides that i changed until what value the for-loop should run, it should run until the end of the array (array.length), not until any other number.
这篇关于使用string.compareTo()插入排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!