Skip to content
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

Implemented/Added #LeetCode324 (Wiggle Sort) to JAVA. #36

Merged
merged 1 commit into from
Oct 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Java/WiggleSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import java.util.Arrays;
import java.util.Scanner;

public class WiggleSort {
public static void wiggleSort(int[] nums) {
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (complexity): Consider using a single-pass in-place swapping approach instead of sorting and cloning the array.

The current implementation unnecessarily sorts the entire array and uses O(n) extra space. The wiggle property can be achieved more efficiently with a single pass and O(1) space complexity. Here's a simpler approach:

public static void wiggleSort(int[] nums) {
    for (int i = 0; i < nums.length - 1; i++) {
        if ((i % 2 == 0) == (nums[i] > nums[i + 1])) {
            // Swap if current relationship doesn't match desired pattern
            int temp = nums[i];
            nums[i] = nums[i + 1];
            nums[i + 1] = temp;
        }
    }
}

This solution:

  • Eliminates extra array allocation
  • Removes the need for sorting
  • Uses a single pass through the array
  • Maintains the wiggle property by ensuring even indices are local minimums and odd indices are local maximums

int n = nums.length;
int[] sorted = nums.clone();
Arrays.sort(sorted);

int j = n - 1;
for (int i = 1; i < n; i += 2) {
nums[i] = sorted[j--];
}

for (int i = 0; i < n; i += 2) {
nums[i] = sorted[j--];
}
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Scanner resource should be closed after use

Consider using try-with-resources to ensure proper closure of the Scanner object.


System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();

int[] nums = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}

wiggleSort(nums);

System.out.println("Wiggled array:");
for (int num : nums) {
System.out.print(num + " ");
}
}
}
Loading