Moving all positive elements to right side (position not preserved)
import java.util.Scanner;
import java.util.ArrayList;
import java.util.*;
class LBArrayPosRightSide{
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 in 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){
end--;
}
else 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{
end--;
}
}
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 Pointers
Comments
Post a Comment