Problem Description:
Given an array of elements consisting of 0, 1, 2. Sort the array.
Example:
{1, 2, 0, 0, 1, 2, 1}
Output:
{0, 0, 1, 1, 1, 2, 2}
Solution explanation:
The solution is very simple, we count the number of 0’s, 1’s and 2’s. Then we put those many 0’s, 1’s and 2’s. Here if you carefully examine, we are not sorting, instead, we are counting and directly adding those many elements in the array.
Solution in C
#include<stdio.h> void sortArray(int arr[], int length) { int count_0 = 0; int count_1 = 0; int count_2 = 0; int itr = 0; for(itr = 0; itr < length; itr ++) { if(arr[itr] == 0) count_0 ++; if(arr[itr] == 1 count_1 ++; if(arr[itr] == 2) count_2 ++; } for (itr = 0; itr < count_0; itr++) { arr[itr] = 0; } for (itr = count_0 ; itr < (count_0+ count_1) ; itr++) { arr[itr] = 1; } for (itr = (count_0+count_1) ; itr < length; itr++) { arr[itr] = 2; } } void printArray(int arr[], int length) { int itr = 0; for (itr = 0; itr < length; ++itr) { printf("%d ", arr[itr] ); } printf("\n"); } int main(int argc, char const *argv[]) { int arr[100] = {1, 2, 0, 0, 1, 2, 1}; int lenght = 7; sortArray(arr, lenght); printArray(arr, lenght); return 0; }
Output:
0 0 1 1 1 2 2
Shivam Prasad
The solurion is ot beautiful. It is dutch national flag problem. Should be solved in a better way.
ajay
Hi Shivam Prasad,
sure shall change add that solution also.