Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Move all negative numbers to beginning and positive to end (java),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]+ " ");}

}

    
}

no error in code,still not getting updated array
where is the mistake?

i tried using three pointers rather than two pointers aooroach,the logic is correct but getting the same array.
geggrsesggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading