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