Skip to content

Commit a51c8c5

Browse files
authored
Merge pull request #547 from sumitvajarinkar/master
Added move-zeroes-end-cpp
2 parents 6641791 + 7b7495c commit a51c8c5

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

Arrays/move_zeroes_end_1traversal.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
}

Arrays/move_zeroes_end_2traversal.cpp

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
}

0 commit comments

Comments
 (0)