-
Notifications
You must be signed in to change notification settings - Fork 20.5k
Fix loops issues #6086
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix loops issues #6086
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -41,12 +41,18 @@ public <T extends Comparable<T>> int find(T[] array, T key) { | |
|
||
int limit = blockSize; | ||
// Jumping ahead to find the block where the key may be located | ||
while (limit < length && key.compareTo(array[limit]) > 0) { | ||
limit = Math.min(limit + blockSize, length - 1); | ||
while (limit < length && key.compareTo(array[Math.min(limit, length - 1)]) > 0) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could you please add your test case, with infinite loop, to |
||
limit += blockSize; | ||
} | ||
|
||
// Handle the case where limit exceeds array length | ||
limit = Math.min(limit, length); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What do you think to rewrite below loop to:
|
||
|
||
// Perform linear search within the identified block | ||
for (int i = limit - blockSize; i <= limit && i < length; i++) { | ||
if (i < 0) { // Skip negative indices | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Looks like, the condition if |
||
continue; | ||
} | ||
if (array[i].equals(key)) { | ||
return i; | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The Math.min in while
(limit < length && key.compareTo(array[Math.min(limit, length - 1)]) > 0)
is a bit redundant because you already checklimit < length
in thewhile
condition.So it can be simplified to: