Skip to content

Commit ba2fe85

Browse files
Updated move-zeroes-end-2-tarversal
1 parent 235483e commit ba2fe85

File tree

1 file changed

+26
-18
lines changed

1 file changed

+26
-18
lines changed

Arrays/move_zeroes_end_2traversal.cpp

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,43 @@
11
//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.
23
//Approach 1
34
//O(n^2) O(1)
45

5-
// i/p: n=5
6-
// 0 1 0 3 12
6+
// i/p: n=5, 0 1 0 3 12
77
// o/p: 1 3 12 0 0
88

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+
919
#include<iostream>
1020
using namespace std;
1121
void moveToEnd(int arr[],int n)
1222
{
1323
for(int i=0;i<n;i++)
1424
{
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+
}
2438
}
2539
}
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+
3341

3442
int main()
3543
{

0 commit comments

Comments
 (0)