-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmoveElements.java
More file actions
107 lines (87 loc) · 2.21 KB
/
Copy pathmoveElements.java
File metadata and controls
107 lines (87 loc) · 2.21 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.lang.Math;
public class moveElements{
public static void main(String[] args)
{
int[] arr={3,0,5,0,1,0,8};
for(int i=0; i< arr.length; i++)
System.out.print(arr[i]+ "\t");
mover move= new mover();
move.moveZeroApproach2(arr);
System.out.println("\n Rotated Array");
for(int i=0; i< arr.length; i++)
{
System.out.print(arr[i]+"\t");
}
}
}
class mover{
public void moveLeftBy1(int[] a)
{
int first= a[0];
for(int i=0; i< a.length -1; i++)
{
a[i]= a[i+1];
}
a[a.length - 1]= first;
}
public void moveLeftByNum(int[] a, int pos)
{
try {
//approach using temporary arr
int n= a.length;
int[] temp= new int[pos];
for(int i=0; i<pos; i++)
{
temp[i]= a[i];
}
//shifting to pos
for(int i=0; i< n; i++)
{
if( i < n-pos)
a[i]= a[i+pos];
else
a[i]= temp[Math.abs(i+2-n)];
}
} catch (Exception e) {
// TODO: handle exception
System.err.println("Moving number cannot be greater then length of array");
}
}
public void moveZeroApproach1(int[] a)
{
for(int i=0; i<a.length-1; i++)
{
for(int j=i; j< a.length-1; j++)
{
if(a[j]== 0)
{
int dummy= a[j];
a[j]= a[j+1];
a[j+1]= dummy;
}
}
}
}
public void moveZeroApproach2(int[] a)
{
//getting p1 and p2 to point first zero element
int p1= -1;
for(int i=0; i< a.length; i++)
{
if (a[i]== 0) {
p1= i;
break;
}
}
for(int i= p1+1; i< a.length ; i++)
{
if(a[i]!=0)
{
// switch cause p position is already pointing to zero
a[p1]= a[i];
a[i]=0;
p1+=1;
}
}
}
}