Skip to content

Implement zero mover algorithm to shift all zeros to the end of array#127

Merged
x0lg0n merged 1 commit intox0lg0n:mainfrom
janvi100104:feature/java
Oct 27, 2025
Merged

Implement zero mover algorithm to shift all zeros to the end of array#127
x0lg0n merged 1 commit intox0lg0n:mainfrom
janvi100104:feature/java

Conversation

@janvi100104
Copy link
Contributor

@janvi100104 janvi100104 commented Oct 27, 2025

Summary by Sourcery

Implement an in-place algorithm to shift all zeros in an array to its end in O(n) time and provide a CLI with a demo fallback for usage.

New Features:

  • Introduce moveZerosToEnd method to relocate zeros to the end of an integer array in-place.
  • Add main method to handle command-line input or run a demo fallback and print the resulting array.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 27, 2025

Reviewer's Guide

Introduces zeroInTheEnd.java with an in-place, O(n)/O(1) algorithm to move zeros to the end of an array and a main method handling input parsing, demo fallback, validation, and formatted output.

Sequence diagram for main method input handling and zero moving

sequenceDiagram
actor User
participant "zeroInTheEnd.main()"
participant "Scanner"
participant "moveZerosToEnd()"
User->>"zeroInTheEnd.main()": Start program
"zeroInTheEnd.main()"->>"Scanner": Read input
alt No input detected
    "zeroInTheEnd.main()"->>"moveZerosToEnd()": Call with demo array
    "moveZerosToEnd()"-->>"zeroInTheEnd.main()": Demo array modified
    "zeroInTheEnd.main()"->>User: Print demo result
else Input detected
    "zeroInTheEnd.main()"->>"Scanner": Read n
    "zeroInTheEnd.main()"->>"Scanner": Read n integers
    "zeroInTheEnd.main()"->>"moveZerosToEnd()": Call with user array
    "moveZerosToEnd()"-->>"zeroInTheEnd.main()": User array modified
    "zeroInTheEnd.main()"->>User: Print result
end
Loading

Class diagram for zeroInTheEnd.java

classDiagram
class zeroInTheEnd {
  +moveZerosToEnd(int[] a)
  +main(String[] args)
}
Loading

File-Level Changes

Change Details Files
Implement zero-to-end algorithm using two pointers
  • Maintain read and write indices to shift non-zero values forward
  • After processing, fill remaining slots with zeros
  • Include JavaDoc specifying O(n) time and O(1) space
Java/zeroInTheEnd.java
Add main method for CLI input, demo fallback, and output formatting
  • Detect missing input to run demo scenario
  • Read array length and elements with validation for insufficient data
  • Assemble output via StringJoiner for space-separated printing
  • Ensure Scanner is closed in a finally block
Java/zeroInTheEnd.java

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link

coderabbitai bot commented Oct 27, 2025

Warning

Rate limit exceeded

@janvi100104 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 13 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 220d1e0 and fc858c4.

📒 Files selected for processing (1)
  • Java/zeroInTheEnd.java (1 hunks)
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@qodo-code-review
Copy link

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
Resource handling risk

Description: The Scanner used for reading from System.in is closed in a finally block, which can
inadvertently close the underlying System.in stream for the entire JVM process if this
code runs within a larger application; prefer not closing System.in or scoping the scanner
to avoid side effects.
zeroInTheEnd.java [24-57]

Referred Code
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	try {
		if (!sc.hasNextInt()) {
			// Demo fallback
			int[] demo = {0, 1, 0, 3, 12, 0, 5};
			System.out.println("No input detected — running demo: " + Arrays.toString(demo));
			moveZerosToEnd(demo);
			System.out.println(Arrays.toString(demo));
			return;
		}

		int n = sc.nextInt();
		int[] a = new int[n];
		for (int i = 0; i < n; i++) {
			if (!sc.hasNextInt()) {
				System.err.println("Expected " + n + " integers but got fewer.");
				return;
			}
			a[i] = sc.nextInt();
		}


 ... (clipped 13 lines)
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

🔴
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status:
Class naming: Class name zeroInTheEnd does not follow Java naming conventions (should be PascalCase like
ZeroInTheEnd) reducing self-documentation quality.

Referred Code
public class zeroInTheEnd {
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
No audit logs: The program performs input processing and array mutation without emitting any audit logs,
but it is unclear whether audit trails are required for this non-critical utility.

Referred Code
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	try {
		if (!sc.hasNextInt()) {
			// Demo fallback
			int[] demo = {0, 1, 0, 3, 12, 0, 5};
			System.out.println("No input detected — running demo: " + Arrays.toString(demo));
			moveZerosToEnd(demo);
			System.out.println(Arrays.toString(demo));
			return;
		}

		int n = sc.nextInt();
		int[] a = new int[n];
		for (int i = 0; i < n; i++) {
			if (!sc.hasNextInt()) {
				System.err.println("Expected " + n + " integers but got fewer.");
				return;
			}
			a[i] = sc.nextInt();
		}


 ... (clipped 10 lines)
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Input edge cases: The code does not validate negative n or excessively large sizes and provides limited
context in error messages, which may be acceptable for a demo CLI but lacks robust
handling.

Referred Code
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
	if (!sc.hasNextInt()) {
		System.err.println("Expected " + n + " integers but got fewer.");
		return;
	}
	a[i] = sc.nextInt();
}
Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Size validation: External input n from Scanner is used to allocate an array without validation (e.g.,
negative or huge values), which could lead to runtime errors or resource issues.

Referred Code
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Rename the class to follow Java naming conventions (e.g., ZeroInTheEnd or ZeroMover) for clarity.
  • Consider extracting the demo and input-handling logic into separate methods or classes to keep the core algorithm focused and easier to test.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Rename the class to follow Java naming conventions (e.g., ZeroInTheEnd or ZeroMover) for clarity.
- Consider extracting the demo and input-handling logic into separate methods or classes to keep the core algorithm focused and easier to test.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@qodo-code-review
Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Add validation for negative array size

Add a check to ensure the user-provided array size n is non-negative, preventing
a potential NegativeArraySizeException.

Java/zeroInTheEnd.java [36-37]

 int n = sc.nextInt();
+if (n < 0) {
+    System.err.println("Array size cannot be negative.");
+    return;
+}
 int[] a = new int[n];
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that a negative input for array size n will cause a NegativeArraySizeException, and the proposed fix improves the program's robustness by handling this edge case.

Medium
  • More

@x0lg0n x0lg0n merged commit 0d82781 into x0lg0n:main Oct 27, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants