-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRearrangeArrayAlternately.java
More file actions
55 lines (44 loc) · 1.04 KB
/
RearrangeArrayAlternately.java
File metadata and controls
55 lines (44 loc) · 1.04 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
public class RearrangeArrayAlternately
{
public static void print(int[] arr)
{
int n=arr.length;
for(int i=0;i<n;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println("");
}
public static int[] rearrange(int arr[], int n)
{
int r=n-1;
int l=0;
int[] a=new int[n];
int j=0;
while(l<r)
{
a[j++]=arr[r];
r--;
a[j++]=arr[l];
l++;
}
if(n%2==1)
{
a[j]=arr[r];
}
for(int i=0;i<n;i++)
{
arr[i]=a[i];
}
return arr;//if you have to return orrignal array
}
//TC:O(N)
//SP:O(N)
public static void main(String[] args)
{
int[] arr = {1,2,3,4,5,6};
print(arr);
int[] ans=rearrange(arr,arr.length);
print(ans);
}
}