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 ?