Home > Back-end >  Why this below code is not returning the desired output ? it should return 1,3,2,2,0,0,0 while its r
Why this below code is not returning the desired output ? it should return 1,3,2,2,0,0,0 while its r

Time:08-03

When I run the below code it's returning same array as output. Can anyone tell me where I am wrong?

public class MoveZeroToend {
    public static void main(String[] args) {
        int[] arr = { 1, 3, 0, 2, 0, 2, 0 };
        Move0Toend(arr);
    }

    static void Move0Toend(int[] arr) { // Code to move zeroes to end
        int count = 0;
        for (int i = 0; i < arr.length; i  ) {
            if (arr[i] != 0) {
                swap(arr[i], arr[count]);
                count  ;
            }
        }
        for (int i = 0; i < arr.length; i  ) {
            System.out.print(arr[i]   " "); // Print the array
        } 
    }

    static void swap(int a, int b) { // To swap
        a = a   b;
        b = a - b;
        a = a - b;
    }
}

CodePudding user response:

on your swap method, you are not swapping the actual values of the objects you've passed, you are swapping between the values passed to the method but there is no result returned so nothing happens. you need to either do the swap on the actual objects - not in a method, or use another way for this. I would recommend googling "pass by value" and "pass by reference". I would also recommend adding a unit test or at least debug the program so you can validate your code is doing what you want.

CodePudding user response:

Your swap method doesn't return any values, nor does it change the values in the reference of the objects passed. To fix this you can either return two values from your swap method (a and b) or you could do it not in a method, that way it would directly affect the objects. Just for a little more explanation, the variables a and b in your swap method are local to the swap method, changing these would not affect any other variables, even if they were also named the same, and as your method is a void it can't return anything. Hope this helps :)

CodePudding user response:

Your swap() method isn't performing any operation on your array, you are just passing two values a and b and swapping them but no operation is being performed on your array.

Instead of passing these two values to your swap() method you can directly swap them inside your for loop as below:

for(int i=0;i<arr.length;i  ){
        if(arr[i]!=0){
            int temp = arr[i];
            arr[i] = arr[count];
            arr[count] = temp;
            count  ;
        }
    }
  • Related