英文:
Java method to confirm the sorting works
问题
我有一个包含100个整数的数组(从0到99),并且我实现了一个Comparable接口。我现在的任务是确认排序是否有效(尽管我知道它有效)。我的代码如下:
public static boolean confirmSorting(Guppy[] sortedArrayOfGuppies) {
boolean confirmed = false;
int maximumID = Integer.MAX_VALUE;
for (Guppy guppy : sortedArrayOfGuppies) {
if (guppy.getIdentificationNumber() < maximumID) {
maximumID = guppy.getIdentificationNumber();
confirmed = true;
}
}
return confirmed;
}
但是即使对于未排序的数组,它也会返回true。我如何确保遍历数组中的每个对象?
不幸的是,https://stackoverflow.com/questions/18111231/how-to-check-if-array-is-already-sorted 提出的解决方案不起作用,因为并非所有整数都是唯一的(有些是相同的)。
英文:
I have an array of 100 ints (from 0 to 99) and I implement a Comparable interface. My task now is to confirm that sorting works (even though I know it does). My code is:
public static boolean confirmSorting(Guppy[] sortedArrayOfGuppies) {
boolean confirmed = false;
int maximumID = Integer.MAX_VALUE;
for (Guppy guppy : sortedArrayOfGuppies) {
if (guppy.getIdentificationNumber() < maximumID) {
maximumID = guppy.getIdentificationNumber();
confirmed = true;
}
}
return confirmed;
}
But it returns true even for unsorted arrays. How do I make sure that iterate through every single object in my array?
Unfortunately, the solution proposed in https://stackoverflow.com/questions/18111231/how-to-check-if-array-is-already-sorted doesn't work, not all ints are unique (some are the same)
答案1
得分: 1
假设它们首先是按顺序排列的。一旦发现不按顺序排列的元素,立即返回。在遇到第一个错误后无需继续检查。这只做了简单的验证,不会打印任何信息。如果按升序排列则返回 true
,否则返回 false
。它还假定 ID 编号是一个 int
。
public static boolean confirmSorting(Guppy[] sortedArrayOfGuppies) {
for (int i = 0; i < sortedArrayOfGuppies.length-1; i++) {
int id1 = sortedArrayOfGuppies[i].getIdentificationNumber();
int id2 = sortedArrayOfGuppies[i+1].getIdentificationNumber();
if (id1 > id2) {
return false;
}
}
return true;
}
注意,你可能希望传入一个 comparator
或 flag
,以便可以验证升序和降序排序。
英文:
Assume they are in sorted order first. Then return as soon as you find ones that aren't. No need to keep checking upon encountering the first failure. This does a simple verification and does not print any information. It returns true
if sorted in ascending order and false
otherwise. It also presumes the id number is an int
.
public static boolean confirmSorting(Guppy[] sortedArrayOfGuppies) {
for (int i = 0; i < sortedArrayOfGuppies.length-1; i++) {
int id1 = sortedArrayOfGuppies[i].getIdentificationNumber();
int id2 = sortedArrayOfGuppies[i+1].getIdentificationNumber();
if (id1 > id2) {
return false;
}
}
return true;
}
Note that you may want to pass in a comparator
or flag
so you can verify both ascending and descending sorts.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论