Skip to content

Instantly share code, notes, and snippets.

@Vishal1297
Created August 27, 2022 12:05
Show Gist options
  • Save Vishal1297/9d0a5810c808a5d1b6ddb6437163d13a to your computer and use it in GitHub Desktop.
Save Vishal1297/9d0a5810c808a5d1b6ddb6437163d13a to your computer and use it in GitHub Desktop.
Solution : Move zeroes to last without maintaining relative order.
public class MoveZeroesWithOutOrder {
public static void main(String[] args) {
int[] arr = {0, 1, 0, 3, 12};
moveZeroes(arr);
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void moveZeroes(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
if (nums[left] == 0 && nums[right] != 0) {
swap(nums, left, right);
left++;
right--;
} else {
if (nums[left] != 0) {
left++;
}
if (nums[right] == 0) {
right--;
}
}
}
}
public static void swap(int[] nums, int left, int right) {
nums[left] = nums[left] + nums[right];
nums[right] = nums[left] - nums[right];
nums[left] = nums[left] - nums[right];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment