Negetive elements on left side of array(position not preserved)
import java.util.Scanner;
import java.util.ArrayList;
import java.util.*;
class LBArrayNegOneSide{
public static void main(String arg[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements in array : ");
int n=sc.nextInt();
int arr[]=new int[n];
System.out.println("Enter elements of array : ");
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int start=0;
int end=n-1;
while(start<end){
if(arr[start]>0 && arr[end]<0){
int temp=0;
temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
else if(arr[start]<0 && arr[end]>0){
start++;
}
else if(arr[start]>0 && arr[end]>0){
end--;
}
else{
start++;
}
}
System.out.println("New Modified array is : ");
for(int i=0;i<n;i++){
System.out.print(arr[i]+" ");
}
}
}
//here we are taking as a category of a negative number
Time: O(n)
Space: O(1)
Concept: Double Pointer
Comments
Post a Comment