Skip to content

Commit fa7cb2b

Browse files
authored
Merge pull request #7 from garud-dwar/garud-dwar-patch-1
Create Sort an array of 0s, 1s and 2s
2 parents 9d2d748 + d806524 commit fa7cb2b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Sort an array of 0s, 1s and 2s

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// C++ program to sort an array
2+
// with 0, 1 and 2 in a single pass
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
// Function to sort the input array,
7+
// the array is assumed
8+
// to have values in {0, 1, 2}
9+
void sort012(int a[], int arr_size)
10+
{
11+
int lo = 0;
12+
int hi = arr_size - 1;
13+
int mid = 0;
14+
15+
// Iterate till all the elements
16+
// are sorted
17+
while (mid <= hi) {
18+
switch (a[mid]) {
19+
20+
// If the element is 0
21+
case 0:
22+
swap(a[lo++], a[mid++]);
23+
break;
24+
25+
// If the element is 1 .
26+
case 1:
27+
mid++;
28+
break;
29+
30+
// If the element is 2
31+
case 2:
32+
swap(a[mid], a[hi--]);
33+
break;
34+
}
35+
}
36+
}
37+
38+
// Function to print array arr[]
39+
void printArray(int arr[], int arr_size)
40+
{
41+
// Iterate and print every element
42+
for (int i = 0; i < arr_size; i++)
43+
cout << arr[i] << " ";
44+
}
45+
46+
// Driver Code
47+
int main()
48+
{
49+
int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
50+
int n = sizeof(arr) / sizeof(arr[0]);
51+
52+
sort012(arr, n);
53+
54+
printArray(arr, n);
55+
56+
return 0;
57+
}
58+
59+
// This code is contributed by Shivi_Aggarwal

0 commit comments

Comments
 (0)