File tree Expand file tree Collapse file tree 2 files changed +90
-0
lines changed Expand file tree Collapse file tree 2 files changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Move all zeros to End
2
+ // Approach 2
3
+ // O(n) O(1)
4
+
5
+
6
+ // i/p: n=5
7
+ // 0 1 0 3 12
8
+ // o/p: 1 3 12 0 0
9
+
10
+ #include < iostream>
11
+ using namespace std ;
12
+ void moveToEnd (int arr[],int n)
13
+ {
14
+ int count=0 ;
15
+ for (int i=0 ;i<n;i++)
16
+ {
17
+ if (arr[i]!=0 )
18
+ {
19
+ swap (arr[i],arr[count]); // if we get 0 we ignore it
20
+ count++; // and if we get non zero we swap with count
21
+ // which point at 0
22
+ }
23
+ }
24
+ }
25
+
26
+ // Here we replace another loop with count
27
+
28
+ int main ()
29
+ {
30
+ int n,i;
31
+ cout<<" Enter the number of elements in array\n " ;
32
+ cin>>n;
33
+ int arr[n];
34
+ cout<<" Enter the elements in array\n " ;
35
+ for (i=0 ;i<n;i++)
36
+ cin>>arr[i];
37
+ moveToEnd (arr,n);
38
+ cout<<" Array having zeroes at end\n " ;
39
+ for (i=0 ;i<n;i++)
40
+ cout<<arr[i]<<" " ;
41
+
42
+ }
Original file line number Diff line number Diff line change
1
+ // Move all zeros to End
2
+ // Approach 1
3
+ // O(n^2) O(1)
4
+
5
+ // i/p: n=5
6
+ // 0 1 0 3 12
7
+ // o/p: 1 3 12 0 0
8
+
9
+ #include < iostream>
10
+ using namespace std ;
11
+ void moveToEnd (int arr[],int n)
12
+ {
13
+ for (int i=0 ;i<n;i++)
14
+ {
15
+ if (arr[i]==0 ) // so we 1st find is there any 0 present
16
+ {
17
+ for (int j=i+1 ;j<n;j++)
18
+ if (arr[j]!=0 ) // if non zero then swap with ith 0
19
+ {
20
+ swap (arr[i],arr[j]); // and swap both
21
+ break ;
22
+ }
23
+ }
24
+ }
25
+ }
26
+ /*
27
+ 5
28
+ 0 0 1 2 3
29
+ 1 0 0 2 3
30
+ 1 2 0 0 3
31
+ 1 2 3 0 0
32
+ */
33
+
34
+ int main ()
35
+ {
36
+ int n,i;
37
+ cout<<" Enter the number of elements in array\n " ;
38
+ cin>>n;
39
+ int arr[n];
40
+ cout<<" Enter the elements in array\n " ;
41
+ for (i=0 ;i<n;i++)
42
+ cin>>arr[i];
43
+ moveToEnd (arr,n);
44
+ cout<<" Array having zeroes at end\n " ;
45
+ for (i=0 ;i<n;i++)
46
+ cout<<arr[i]<<" " ;
47
+
48
+ }
You can’t perform that action at this time.
0 commit comments