If there is no odd value to the right of the zero, leave the zero as a zero.
zeroMax([0, 5, 0, 3]) → [5, 5, 3, 3]
zeroMax([0, 4, 0, 3]) → [3, 4, 3, 3]
This is from CodingBat: https://codingbat.com/prob/p187050
There are certainly better implementations than mine, but it would help me tremendously to see where I went wrong.
It is the findAndReplace method that is not doing its job. I don't see a reason as to why it insists that intarray[0] = 0, and that is where I am stuck. I have implemented the method separately from this class, and it works as expected.
Below is my work:
public class ZeroMax {
public static int[] zeroMax(int[] intarray) {
int max = largestOdd(intarray);
System.out.println("largest odd is " + max);
return findAndReplace1(intarray, 0, max);
}
//method returns the largest odd value or returns zero
public static int largestOdd(int[] arr) {
int maxodd = 0;
int n = arr.length;
int temp = 0;
//this is just a bubble sort
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (arr[j - 1] > arr[j]) {
//swap elements
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
//this finds the largest number that is an odd
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] % 2 != 0) {
maxodd = arr[i];
break;
} else {
continue;
}
}
return maxodd;
}
//following returns an array where the zeros (int find)
// can be replaced with the largest odd (int replace)
public static int[] findAndReplace1(int[] intarray, int find, int replace) {
for (int i = 0; i < intarray.length; i++) {
//System.out.println(intarray[i]);
if (intarray[i] == find) {
intarray[i] = replace;
}
}
return intarray;
}
}
I believe that the key to your problem is
… to the right of the zero in the array
One given example is zeroMax([0, 5, 0, 3]) → [5, 5, 3, 3]. In your code you are finding the greatest odd value in the entire array. 5 in this case. Then you are replacing every 0 in the array with 5.
Original array: [0, 5, 0, 3]
Expected result: [5, 5, 3, 3]
Your result: [5, 5, 5, 3]
So it seems that you still have a bit of coding to do.
There are certainly better implementations than mine, …
Your implementation, your design and code style, are just fine. Only except for the lamentable fact that it didn’t solve the problem correctly.
An idea how to solve the problem. The following should work in all cases:
Iterate backward from the end array until the first (so the rightmost) odd number.
If there isn’t any odd number in the array, you’re done.
Store the odd number into a variable holding the greatest odd number encountered so far.
Continue iterating backward from the index you came to down to index 0. For each index:
If the number at the index is odd and greater than the hitherto greatest odd number, store the number as the greatest odd number.
If the number is 0, store the greatest odd number until now into the array at this index.
I was reading the question wrong. This is the successful solution that I came up with after more careful reading:
public int[] zeroMax(int[] intarray) {
int maxvalue = 0;
int index = 0;
for (int i = 0; i < intarray.length; i++) {
if (intarray[i] == 0) {
index = i;
//call max value method
maxvalue = maxvalue(intarray, index);
intarray[i] = maxvalue;
}
}
return intarray;
}
public int maxvalue(int[] intarray, int index) {
int maxvalue = 0;
for (int i = index; i < intarray.length; i++) {
if ((intarray[i] % 2 == 1) && (intarray[i] > maxvalue)) {
maxvalue = intarray[i];
}
}
return maxvalue;
}
You can use Arrays.stream(T[],int,int) method to iterate over this array from the current index to the end, then filter odd numbers and get max of them:
public static void main(String[] args) {
int[] arr1 = {0, 5, 0, 3};
int[] arr2 = {0, 4, 0, 3};
int[] arr3 = {0, 3, 0, 4};
replaceZeros(arr1);
replaceZeros(arr2);
replaceZeros(arr3);
System.out.println(Arrays.toString(arr1)); // [5, 5, 3, 3]
System.out.println(Arrays.toString(arr2)); // [3, 4, 3, 3]
System.out.println(Arrays.toString(arr3)); // [3, 3, 0, 4]
}
private static void replaceZeros(int[] arr) {
// iterate over the indices of array
IntStream.range(0, arr.length)
// filter zero elements
.filter(i -> arr[i] == 0)
// for each zero iterate over the elements
// of array from the current index to the end
.forEach(i -> Arrays.stream(arr, i, arr.length)
// filter odd elements
.filter(e -> e % 2 != 0)
// take the max element and
// replace the current one
.max().ifPresent(e -> arr[i] = e));
}
I am currently practicing algorithm development with Java and have recently really got stuck on a particular problem. I have been challenged to develop two different algorithm.
My task is to solve the selection problem. the selection problem determines the kth largest number in a group of N numbers.
I have successfully implemented the first algorithm. I read the N numbers into an array, sort the array in decreasing order by some simple algorithm, and then return the element in position k.
Note: k = N / 2
Here is the working code
public int selectionAlgorithmOne() {
int[] intArray = new int[]{1, 7, 9, 8, 2, 3, 5, 4, 6, 10};
//I sort the array of size N in decreasing order
bubbleSortDecreasingOrder(intArray);
//{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
//I obtain the value of k
int k = intArray.length / 2;
//I print the result
System.out.println(intArray[k]);
}
The value that is printed in "5" which is correct! However, the second algorithm is a bit trickier.
Read the first k elements into an array and sort them in decreasing order. Next, each remaining element is read one by one. As a new element arrives, it is ignored if it is smaller than the kth element in the array. Otherwise, it is placed in its correct spot in the array, bumping one element out of the array. When the algorithm ends, the element in the kth position is returned as the answer.
Unfortunately my second algorithm does not work. It returns the value "3" which is wrong. It should be returning the same value of "5" as the first algorithm but in a more efficient.
I have been stuck for a few days now and I am really struggling to find the solution. Hopefully I have given the problem enough context, let me know if I can provide any more information. Thanks in advance.
Here is the non-working code
public int selectionAlgorithmTwo() {
int[] intArray = new int[]{1, 7, 9, 8, 2, 3, 5, 4, 6, 10};
int arrayLength = intArray.length;
int k = arrayLength / 2;
int[] firstHalf = new int[k];
//I read the first half of the elements into an array
for (int i = 0; i < k; i++) {
firstHalf[i] = intArray[i];
}
//I then sort the first half of the elements in decreasing order
bubbleSort(firstHalf);
for(int i = k; i < arrayLength; i++) {
int val = intArray[i];
//If the new element to insert is >= the kth largest
if (val > firstHalf[k - 1]) {
int pos = 0;
for(; pos < k; pos++) {
if(val > firstHalf[pos]) {
break; //I break once I have the correct position located
}
//I make the swap
for (int j = k - 1; j > pos; j--)
firstHalf[j] = firstHalf[j - 1];
firstHalf[pos] = val;
}
}
}
return firstHalf[k - 1];
}
First of all, "the element in position k" isn't the kth element, it's the k+1 th element. Indeed 5 is the sixth element of the sorted array.
So, if you want to return the element in position k, you need an array of k+1 element.
Therefore I added the firstHalfLen variable.
If you use an array of k element, you'll never get 5 as answer.
In the block if (val > firstHalf[k]), in order to find the correct index, I preferred a while loop
while ((pos < firstHalfLen) && (val <= firstHalf[pos])) {
pos++;
}
Then the swap:
for (int j = k; j > pos; j--) {
firstHalf[j] = firstHalf[j - 1];
}
Code:
int[] intArray = new int[] { 1, 7, 9, 8, 2, 3, 5, 4, 6, 10 };
int arrayLength = intArray.length;
int k = arrayLength / 2;
int firstHalfLen = k + 1;
int[] firstHalf = new int[firstHalfLen];
// I read the first half of the elements into an array
for (int i = 0; i < firstHalfLen; i++) {
firstHalf[i] = intArray[i];
}
//I then sort the first half of the elements in decreasing order
bubbleSort(firstHalf);
for (int i = firstHalfLen; i < arrayLength; i++) {
int val = intArray[i];
// If the new element to insert is >= the kth largest
if (val > firstHalf[k]) {
int pos = 0;
// find index
while ((pos < firstHalfLen) && (val <= firstHalf[pos])) {
pos++;
}
// Swap
for (int j = k; j > pos; j--) {
firstHalf[j] = firstHalf[j - 1];
}
firstHalf[pos] = val;
}
}
return firstHalf[k];
You are comparing values from the unsorted part to values of the sorted part, starting low, i.e. at small values. The probability that the value is larger than the first sorted value is quite high. More interesting would be a value which is smaller. According to your algorithm, the smaller unsorted value should be inserted into the small sorted values, at the position where it replaces a higher value, not a smaller one.
So
if(val > firstHalf[pos])
should be
if(val < firstHalf[pos])
Try this code:
public int sortTest() {
int[] intArray = new int[]{1, 7, 9, 8, 2, 3, 5, 4, 6, 10};
int arrayLength = intArray.length;
int k = arrayLength / 2;
int[] firstHalf = new int[k];
//I read the first half of the elements into an array
for (int i = 0; i < k; i++) {
firstHalf[i] = intArray[i];
}
//I then sort the first half of the elements in decreasing order
bubbleSort(firstHalf);
for(int i = k; i < arrayLength; i++) {
int val = intArray[i];
//If the new element to insert is >= the kth largest
if (val > firstHalf[k - 1]) {
int pos = 0;
for(; pos < k; pos++) {
if(val > firstHalf[pos]) {
break; //I break once I have the correct position located
}
}
//I make the swap
for (int j = k - 1; j > pos; j--)
firstHalf[j] = firstHalf[j - 1];
firstHalf[pos] = val;
}
}
return firstHalf[k - 1];
}
The error in your code is that, after you found the correct position and break, you leave the for loop without the swap procedure.
Also note that this code return 6, not 5, because you returned the k-1 th value.
I am trying to write a method which takes an array of ints and then rearranges the numbers in the array so that the negative numbers come first. The array does not need to be sorted in any way. The only requirement is that the solution has to be linear and it does not use an extra array.
Input:
{1, -5, 6, -4, 8, 9, 4, -2}
Output:
{-5, -2, -4, 8, 9, 1, 4, 6}
Now as a noob in Java and programming in general I am not 100% sure on what is considered a linear solution, but my guess is that it has to be a solution that does not use a loop within a loop.
I currently have an awful solution that I know doesn't work (and I also understand why) but I can't seem to think of any other solution. This task would be easy if I were allowed to use a loop within a loop or an additional array but I am not allowed to.
My code:
public static void separateArray(int[] numbers) {
int i = 0;
int j = numbers.length-1;
while(i<j){
if(numbers[i] > 0){
int temp;
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
System.out.println(Arrays.toString(numbers));
}
i++;
j--;
}
}
You only need to change one line to get it (mostly) working. But you need to change two lines to correctly handle zeroes in the input. I have highlighted both of these minimally necessary changes with "FIXME" comments below:
public static void separateArray(int[] numbers) {
int i = 0;
int j = numbers.length-1;
while(i<j){
if(numbers[i] > 0){ // FIXME: zero is not a "negative number"
int temp;
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
i++; // FIXME: only advance left side if (numbers[i] < 0)
j--; // FIXME: only decrease right side if (numbers[j] >= 0)
}
}
Your approach with two pointers, i and j is a good start.
Think about the loop invariant that you immediately set up (vacuously):
Elements in the range 0 (inclusive) to i (exclusive) are negative;
Elements in the range j (exclusive) to numbers.length (exclusive) are non-negative.
Now, you want to be able to move i and j together until they pass each other, preserving the loop invariant:
If i < numbers.length and numbers[i] < 0, you can increase i by 1;
If j >= 0 and numbers[j] >= 0, you can decrease j by 1;
If i < numbers.length and j >= 0, then numbers[i] >= 0 and numbers[j] < 0. Swap them around.
If you keep applying this strategy until i == j + 1, then you end up with the desired situation, that:
numbers[a] < 0 for a in [0..i)
numbers[a] >= 0 for a in (j..numbers.length), also written as numbers[a] >= 0 for a in (i-1..numbers.length), also written as numbers[a] >= 0 for a in [i..numbers.length).
So, you've partitioned the array so that all negative numbers are on the left of the i-th element, and all non-negative numbers are at or to the right of the i-th element.
Hopefully, this algorithm should be easy to follow, and thus to implement.
A linear solution is a solution with a run-time complexity Big-Oh(n) also noted as O(n), in other words, you have to loop through the whole array only once. To sort in linear time you can try one of the following sorting algorithms:
Pigeonhole sort
Counting sort
Radix sort
Your code works only if all the negative numbers are located in the right half side and the positives in the left half. For example, your code swaps 6 with 9 which both are positives. So, it depends on the order of your the array elements. As scottb said, try do it by your hands first then you will notice where you did wrong. Moreover, print your array out of the while
//Move positive number left and negative number right side
public class ArrangeArray {
public static void main(String[] args) {
int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
for (int i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}
int temp = 0;
for (int i = 0; i < arr.length; i++) {
// even
if (arr[i] < 0) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] > 0) {
arr[j] = arr[i] + arr[j];
arr[i] = arr[j] - arr[i];
arr[j] = arr[j] - arr[i];
break;
}
}
}
}
System.out.println("");
for (int i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}
}
}
There is simple program it will help you. In this program i have take temp array and perform number of item iteration. In that i have start fill positive value from right and negative from left.
public static void rearrangePositiveAndNegativeValues() {
int[] a = {10,-2,-5,5,-8};
int[] b = new int[a.length];
int i = 0, j = a.length -1;
for (int k = 0; k < a.length ; k++) {
if (a[k] > 0) {
b[j--] = a[k];
} else {
b[i++] = a[k];
}
}
System.out.println("Rearranged Values : ");
printArray(b);
}
package ArrayProgramming;
import java.util.ArrayList;
import java.util.Arrays;
public class RearrangingpossitiveNegative {
public static void main(String[] args) {
int[] arr= {-1,3,4,5,-6,6,8,9,-4};
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i=0;i<arr.length;i++) {
if(arr[i]>0) {
al.add(arr[i]);
}
}
for (int i=arr.length-1;i>=0;i--) {
if(arr[i]<0) {
al.add(arr[i]);
}
}
System.out.println(al);
}
}
from array import *
size = int(input())
arr = (array('i' , list(map(int, input().split()))))
negarr = array('i')
posarr = array('i')
for i in arr:
if i>=0:
posarr.append(i)
else:
negarr.append(i)
print(*(negarr+posarr))
we can also do it by creating two new arrays and adding elements into them as per given condition. later joining both of them to produce final result.
I need to move all 0's in an array to the end of the array.
Example: [1, 10, 0, 5, 7] should result in [1, 10, 5, 7, 0].
I am open to doing a reverse loop or a regular loop.
I cannot create a new array.
Here is what I have so far:
for (int i = arr.length; i <= 0; --i) {
if (arr[i] != 0) {
arr[i] = arr.length - 1;
}
}
Thanks!
SIZE(n) where n = arr.size, retain ordering:
Create an array that is the same size as the initial array you need to remove 0s from. Iterate over the original array and add each element to the new array provided it is not 0. When you encounter a 0, count it. Now, when you've reached the end of the first array, simply add the counted number of 0s to the end of the array. And, even simpler, since Java initializes arrays to 0, you can forget about adding the zeroes at the end.
Edit
Since you have added the additional constraint of not being able to create a new array, we need to take a slightly different approach than the one I've suggested above.
SIZE(1)
I assume the array needs to remain in the same order as it was before the 0s were moved to the end. If this is not the case there is another trivial solution as detailed in Brads answer: initialize a "last zero" index to the last element of the array and then iterate backwards swapping any zeros with the index of the last zero which is decremented each time you perform a swap or see a zero.
SIZE(1), retain ordering:
To move the 0s to the end without duplicating the array and keeping the elements in the proper order, you can do exactly as I've suggested without duplicating the array but keeping two indices over the same array.
Start with two indices over the array. Instead of copying the element to the new array if it is not zero, leave it where it is and increment both indices. When you reach a zero, increment only one index. Now, if the two indices are not the same, and you are not looking at a 0, swap current element the location of the index that has fallen behind (due to encountered 0s). In both cases, increment the other index provided the current element is not 0.
It will look something like this:
int max = arr.length;
for (int i = 0, int j = 0; j < max; j++) {
if (arr[j] != 0) {
if (i < j) {
swap(arr, i, j);
}
i++
}
}
Running this on:
{ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 }
yeilds:
{ 1, 2, 3, 4, 5, 0, 0, 0, 0, 0 }
I made a fully working version for anyone who's curious.
Two choices come to mind
Create a new array of the same size, then Iterate over your current array and only populate the new array with values. Then fill the remaining entries in the new array with "zeros"
Without creating a new array you can iterate over your current array backwards and when you encounter a "zero" swap it with the last element of your array. You'll need to keep a count of the number of "zero" elements swapped so that when you swap for a second time, you swap with the last-1 element, and so forth.
[Edit] 7 years after originally posting to address the "ordering" issue and "last element is zero" issues left in the comments
public class MyClass {
public static void main(String[] args) {
int[] elements = new int[] {1,0,2,0,3,0};
int lastIndex = elements.length-1;
// loop backwards looking for zeroes
for(int i = lastIndex; i >=0; i--) {
if(elements[i] == 0) {
// found a zero, so loop forwards from here
for(int j = i; j < lastIndex; j++) {
if(elements[j+1] == 0 || j == lastIndex) {
// either at the end of the array, or we've run into another zero near the end
break;
}
else {
// bubble up the zero we found one element at a time to push it to the end
int temp = elements[j+1];
elements[j+1] = elements[j];
elements[j] = temp;
}
}
}
}
System.out.println(Arrays.toString(elements));
}
}
Gives you...
[1, 2, 3, 0, 0, 0]
Basic solution is to establish an inductive hypothesis that the subarray can be kept solved. Then extend the subarray by one element and maintain the hypothesis. In that case there are two branches - if next element is zero, do nothing. If next element is non-zero, swap it with the first zero in the row.
Anyway, the solution (in C# though) after this idea is optimized looks like this:
void MoveZeros(int[] a)
{
int i = 0;
for (int j = 0; j < a.Length; j++)
if (a[j] != 0)
a[i++] = a[j];
while (i < a.Length)
a[i++] = 0;
}
There is a bit of thinking that leads to this solution, starting from the inductive solution which can be formally proven correct. If you're interested, the whole analysis is here: Moving Zero Values to the End of the Array
var size = 10;
var elemnts = [0, 0, 1, 4, 5, 0,-1];
var pos = 0;
for (var i = 0; i < elemnts.length; i++) {
if (elemnts[i] != 0) {
elemnts[pos] = elemnts[i];
pos++;
console.log(elemnts[i]);
}
}
for (var i = pos; i < elemnts.length; i++) {
elemnts[pos++] = 0;
console.log(elemnts[pos]);
}
int arrNew[] = new int[arr.length];
int index = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]!=0){
arrNew[index]=arr[i];
index++;
}
}
Since the array of int's is initialized to zero(according to the language spec). this will have the effect you want, and will move everything else up sequentially.
Edit: Based on your edit that you cannot use a new array this answer doesnt cover your requirements. You would instead need to check for a zero(starting at the end of the array and working to the start) and swap with the last element of the array and then decrease the index of your last-nonzero element that you would then swap with next. Ex:
int lastZero = arr.length - 1;
if(arr[i] == 0){
//perform swap and decrement lastZero by 1 I will leave this part up to you
}
/// <summary>
/// From a given array send al zeros to the end (C# solution)
/// </summary>
/// <param name="numbersArray">The array of numbers</param>
/// <returns>Array with zeros at the end</returns>
public static int[] SendZerosToEnd(int[] numbersArray)
{
// Edge case if the array is null or is not long enough then we do
// something in this case we return the same array with no changes
// You can always decide to return an exception as well
if (numbersArray == null ||
numbersArray.Length < 2)
{
return numbersArray;
}
// We keep track of our second pointer and the last element index
int secondIndex = numbersArray.Length - 2,
lastIndex = secondIndex;
for (int i = secondIndex; i >= 0; i--)
{
secondIndex = i;
if (numbersArray[i] == 0)
{
// While our pointer reaches the end or the next element
// is a zero we swap elements
while (secondIndex != lastIndex ||
numbersArray[secondIndex + 1] != 0)
{
numbersArray[secondIndex] = numbersArray[secondIndex + 1];
numbersArray[secondIndex + 1] = 0;
++secondIndex;
}
// This solution is like having two pointers
// Also if we look at the solution you do not pass more than
// 2 times actual array will be resume as O(N) complexity
}
}
// We return the same array with no new one created
return numbersArray;
}
In case if question adds following condition.
Time complexity must be O(n) - You can iterate only once.
Extra
space complexity must be O(1) - You cannot create extra array.
Then following implementation will work fine.
Steps to be followed :
Iterate through array & maintain a count of non-zero elements.
Whenever we encounter a non-zero element put at count location in array & also increase the count.
Once array is iterated completely put the zeros at end of array till the count reach to original length of array.
public static void main(String args[]) {
int[] array = { 1, 0, 3, 0, 0, 4, 0, 6, 0, 9 };
// Maintaining count of non zero elements
int count = -1;
// Iterating through array and copying non zero elements in front of array.
for (int i = 0; i < array.length; i++) {
if (array[i] != 0)
array[++count] = array[i];
}
// Replacing end elements with zero
while (count < array.length - 1)
array[++count] = 0;
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Time complexity = O(n), Space Complexity = O(1)
import java.util.Scanner;
public class ShiftZeroesToBack {
int[] array;
void shiftZeroes(int[] array) {
int previousK = 0;
int firstTime = 0;
for(int k = 0; k < array.length - 1; k++) {
if(array[k] == 0 && array[k + 1] != 0 && firstTime != 0) {
int temp = array[previousK];
array[previousK] = array[k + 1];
array[k + 1] = temp;
previousK = previousK + 1;
continue;
}
if(array[k] == 0 && array[k + 1] != 0) {
int temp = array[k];
array[k] = array[k + 1];
array[k + 1] = temp;
continue;
}
if(array[k] == 0 && array[k + 1] == 0) {
if(firstTime == 0) {
previousK = k;
firstTime = 1;
}
}
}
}
int[] input(Scanner scanner, int size) {
array = new int[size];
for(int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
return array;
}
void print() {
System.out.println();
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ShiftZeroesToBack sztb = new ShiftZeroesToBack();
System.out.print("Enter Size of Array\t");
int size = scanner.nextInt();
int[] input = sztb.input(scanner, size);
sztb.shiftZeroes(input);
sztb.print();
}
}
let's say we have an array
[5,4,0,0,6,7,0,8,9]
Let's assume we have array elements between 0-100, now our goal is to move all 0's at the end of the array.
now hold 0 from the array and check it with non zero element if any non zero element found swap with that element and so on, at the end of the loop we will find the solution.
here is the code
for (int i = 0; i < outputArr.length; i++)
{
for (int j = i+1; j < outputArr.length; j++)
{
if(outputArr[i]==0 && outputArr[j]!=0){
int temp = outputArr[i];
outputArr[i] = outputArr[j];
outputArr[j] = temp;
}
}
print outputArr[i]....
}
output:
[5,4,6,7,8,9,0,0,0]
Here is how i have implemented this.
Time complexity: O(n) and Space Complexity: O(1)
Below is the code snippet:
int arr[] = {0, 1, 0, 0, 2, 3, 0, 4, 0};
int i=0, k = 0;
int n = sizeof(arr)/sizeof(arr[0]);
for(i = 0; i<n; i++)
{
if(arr[i]==0)
continue;
arr[k++]=arr[i];
}
for(i=k;i<n;i++)
{
arr[i]=0;
}
output: {1, 2, 3, 4, 0, 0, 0, 0, 0}
Explanation: using another variable k to hold index location, non-zero elements are shifted to the front while maintaining the order. After traversing the array, non-zero elements are shifted to the front of array and another loop starting from k is used to override the remaining positions with zeros.
This is my code with 2 for loops:
int [] arr = {0, 4, 2, 0, 0, 1, 0, 1, 5, 0, 9,};
int temp;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] != 0)
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
break;
}
}
}
}
System.out.println(Arrays.toString(arr));
output: [4, 2, 1, 1, 5, 9, 0, 0, 0, 0, 0]
public static void main(String[] args) {
Integer a[] = {10,0,0,0,6,0,0,0,70,6,7,8,0,4,0};
int flag = 0;int count =0;
for(int i=0;i<a.length;i++) {
if(a[i]==0 ) {
flag=1;
count++;
}else if(a[i]!=0) {
flag=0;
}
if(flag==0 && count>0 && a[i]!=0) {
a[i-count] = a[i];
a[i]=0;
}
}
}
This is One method of Moving the zeroes to the end of the array.
public class SeparateZeroes1 {
public static void main(String[] args) {
int[] a = {0,1,0,3,0,0,345,12,0,13};
movezeroes(a);
}
static void movezeroes(int[] a) {
int lastNonZeroIndex = 0;
// If the current element is not 0, then we need to
// append it just in front of last non 0 element we found.
for (int i = 0; i < a.length; i++) {
if (a[i] != 0 ) {
a[lastNonZeroIndex++] = a[i];
}
}//for
// We just need to fill remaining array with 0's.
for (int i = lastNonZeroIndex; i < a.length; i++) {
a[i] = 0;
}
System.out.println( lastNonZeroIndex );
System.out.println(Arrays.toString(a));
}
}
This is very simple in Python. We will do it with list comprehension
a =[0,1,0,3,0,0,345,12,0,13]
def fix(a):
return ([x for x in a if x != 0] + [x for x in a if x ==0])
print(fix(a))
int[] nums = { 3, 1, 2, 5, 4, 6, 3, 2, 1, 6, 7, 9, 3, 8, 0, 4, 2, 4, 6, 4 };
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 3) {
list1.add(nums[i]);
} else if (nums[i] != 3) {
list2.add(nums[i]);
}
}
List<Integer> finalList = new ArrayList<>(list2);
finalList.addAll(list1);
}
}
int[] nums = {3,1,2,5,4,6,3,2,1,6,7,9,3,8,0,4,2,4,6,4};
int i = 0;
for(int j = 0, s = nums.length; j < s;) {
if(nums[j] == 3)
j++;
else {
int temp = nums[i];
nums[i] = nums[j];``
nums[j] = temp;
i ++;
j ++;
}
}
For Integer array it can be as simple as
Integer[] numbers = { 1, 10, 0, 5, 7 };
Arrays.sort(numbers, Comparator.comparing(n -> n == 0));
For int array :
int[] numbers = { 1, 10, 0, 5, 7 };
numbers = IntStream.of(numbers).boxed()
.sorted(Comparator.comparing(n -> n == 0))
.mapToInt(i->i).toArray();
Output of both:
[1, 10, 5, 7, 0]
Lets say, you have an array like
int a[] = {0,3,0,4,5,6,0};
Then you can sort it like,
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++){
if(a[i]==0 && a[j]!=0){
a[i]==a[j];
a[j]=0;
}
}
}
public void test1(){
int [] arr = {0,1,0,4,0,3,2};
System.out.println("Lenght of array is " + arr.length);
for(int i=0; i < arr.length; i++){
for(int j=0; j < arr.length - i - 1; j++){
if(arr[j] == 0){
int temp = arr[j];
arr[j] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
}
}
for(int x = 0; x < arr.length; x++){
System.out.println(arr[x]);
}
}
Have a look at this function code:
vector<int> Solution::solve(vector<int> &arr) {
int count = 0;
for (int i = 0; i < arr.size(); i++)
if (arr[i] != 0)
arr[count++] = arr[i];
while (count < arr.size())
arr[count++] = 0;
return arr;
}
import java.io.*;
import java.util.*;
class Solution {
public static int[] moveZerosToEnd(int[] arr) {
int j = 0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] != 0) {
swap(arr, i, j);
j++;
}
}
return arr;
}
private static void swap(int arr[], int i, int j){
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
public static void main(String[] args) {
int arr[] =new int[] {1, 10, 0, 2, 8, 3, 0, 0, 6, 4, 0, 5, 7, 0 };
System.out.println(Arrays.toString(moveZerosToEnd(arr)));
}
}
Reimplemented this in Python:
Pythonic way:
lst = [ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 ]
for i, val in enumerate(lst):
if lst[i] == 0:
lst.pop(i)
lst.append(0)
print("{}".format(lst))
#dcow's implementation in python:
lst = [ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 ]
i = 0 # init the index value
for j in range(len(lst)): # using the length of list as the range
if lst[j] != 0:
if i < j:
lst[i], lst[j] = lst[j], lst[i] # swap the 2 elems.
i += 1
print("{}".format(lst))
a = [ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 ]
count = 0
for i in range(len(a)):
if a[i] != 0:
a[count], a[i] = a[i], a[count]
count += 1
print(a)
#op [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]