Skip to content

Commit

Permalink
Implemented/Added #LeetCode324 (Wiggle Sort)
Browse files Browse the repository at this point in the history
Problem: Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

You may assume the input array always has a valid answer.

Example 1:

Input: nums = [1,5,1,1,6,4]
Output: [1,6,1,5,1,4]
Explanation: [1,4,1,5,1,6] is also accepted.
  • Loading branch information
naman648 authored and x0lg0n committed Oct 30, 2024
1 parent a522298 commit 64234f4
Showing 1 changed file with 39 additions and 0 deletions.
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) {
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);

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 + " ");
}
}
}

0 comments on commit 64234f4

Please sign in to comment.