forked from Jasmine-21/Java-FOP
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathalternateposndneg.java
More file actions
67 lines (59 loc) · 2.01 KB
/
alternateposndneg.java
File metadata and controls
67 lines (59 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.*;
public class alternateposndneg {
void rightrotate(int arr[], int n, int outofplace, int cur)
{
int tmp = arr[cur];
for (int i = cur; i > outofplace; i--)
arr[i] = arr[i - 1];
arr[outofplace] = tmp;
}
void rearrange(int arr[], int n)
{
int outofplace = -1;
for (int index = 0; index < n; index++)
{
if (outofplace >= 0)
{
if (((arr[index] >= 0) && (arr[outofplace] < 0))
|| ((arr[index] < 0) && (arr[outofplace] >= 0)))
{
rightrotate(arr, n, outofplace, index);
// the new out-of-place entry is now 2 steps ahead
if (index - outofplace > 2)
outofplace = outofplace + 2;
else
outofplace = -1;
}
}
// if no entry has been flagged out-of-place
if (outofplace == -1)
{
// check if current entry is out-of-place
if (((arr[index] >= 0) && ((index & 0x01)==0))
|| ((arr[index] < 0) && (index & 0x01)==1))
outofplace = index;
}
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
public static void main(String[] args) {
alternateposndneg rearrange = new alternateposndneg();
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Given array is ");
rearrange.printArray(arr, n);
rearrange.rearrange(arr, n);
System.out.println("RearrangeD array is ");
rearrange.printArray(arr, n);
}
}