-2

What is the Time & Space Complexity of this code ?

Here,is the code for moving all the negative elements of any array to the end of the array while maintaining the order of all non-negative elements as well as negative elements - as,

Input : {-11,-1,3, 24, -7, -5, 11, -6}

Output : {3, 24, 11, -11, -1, -7, -5, -6}

public static void MoveNegativeElementsToEnd(int arr[])
    {
        int k=arr.length-1;
        int n=arr.length;

        for(int i=n-1;i>=0;i--){
            if(arr[i]<0){
                for(int j=i;j<k;j++){
                    swap(arr,j,j+1);
                }
                k--;
            }
        }
    }
    public static void swap(int[] arr, int a, int b){
        int temp=arr[a];
        arr[a]=arr[b];
        arr[b]=temp;
    }

Acco. to me, time complexity is O(N^2),

n -> for traversing the array

n -> for swapping the negative elements to the end each time. Is this correct ?

And is the space complexity is O(1) as, for all the inputs it takes the same no. of variables ?

Nandini Agarwal
  • 91
  • 1
  • 10

1 Answers1

1

The inner loop runs for n-1-i times (when it runs). Assuming the probability p of an array element to be negative, every element contributes p(n-1-i) swaps. Now you sum this for i in [n-1, 0], i.e. n-1-i in [0, n-1], and the expected cost is

p(n-1)n/2

swaps.