File tree Expand file tree Collapse file tree 1 file changed +26
-18
lines changed Expand file tree Collapse file tree 1 file changed +26
-18
lines changed Original file line number Diff line number Diff line change 1
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.
2
3
// Approach 1
3
4
// O(n^2) O(1)
4
5
5
- // i/p: n=5
6
- // 0 1 0 3 12
6
+ // i/p: n=5, 0 1 0 3 12
7
7
// o/p: 1 3 12 0 0
8
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
+
9
19
#include < iostream>
10
20
using namespace std ;
11
21
void moveToEnd (int arr[],int n)
12
22
{
13
23
for (int i=0 ;i<n;i++)
14
24
{
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
- }
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
+ }
24
38
}
25
39
}
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
- */
40
+
33
41
34
42
int main ()
35
43
{
You can’t perform that action at this time.
0 commit comments