Sort an array of 0s, 1s and 2s-Data Structures
Sort an array of 0s, 1s and 2s-Data Structures
Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order
Example :
Input:
N = 4
arr[] = {0 1 0 2}
Output:
0 0 1 2
Explanation:
0s 1s and 2s are segregated
into ascending order
Solution:
void sort012(int a[], int n)
{
int low = 0;
int high = n - 1;
int mid = 0;
while (mid <= high)
{
if (a[mid] == 0)
{
swap(a[low], a[mid]);
low++;
mid++;
}
else if (a[mid] == 1)
{
mid++;
}
else
{
swap(a[mid], a[high]);
high--;
}
}
}
Thank You.
No comments:
Post a Comment