Search code examples
javaarraysbinary-search

Move all negative numbers to beginning and positive to end, order is not important


public class posbeginnegend {

    private static void Swap(int a, int b) {
        int temp=a;
        a=b;
        b=temp;
    }

    public static void main(String[] args) {
        int []arr={45,23,-89,-21,67,-34,7,-44};

        int start=0;
        int end=arr.length-1;

        while(start<=end)
        {
            int mid=start+(end-start)/2;

            if(arr[mid]>0)
            {   if(arr[end]>0)
                {
                    end--;
                }
                else
                {
                    Swap(arr[mid],arr[end]);
                    end--;
                }
            }
            else
            {
                if(arr[start]<0)
                {   
                    start++;
                }
                else
                {
                    Swap(arr[mid],arr[start]);
                    start++;
                }
            }
        }
        for(int i=0;i<=arr.length-1;i++)
        {System.out.print(arr[i]+ " ");}
    }
}

There is no error in my code, but I do not get an updated array. Where is my mistake?

I tried using three pointers rather than two pointers approach. The logic is correct, but I get the same array.


Solution

  • Swap() (should be swap() by convention) is changing internal values. java is pass-by-value. instead of passing the values, you need to pass the array itself and the indices to swap

    private static void Swap(int[] arr, int i1, int i2) {
        int temp = arr[i1];
        arr[i1] = arr[i2];
        arr[i2] = temp;
    }