0
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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

0

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;
}
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
0

You can use Collections.sort() to sort the numbers.

Mina Abd El-Massih
  • 636
  • 1
  • 8
  • 13
john doe
  • 1
  • 2