Learn-dsa..in 30 days!



























CC-14 : Sort array of 0s, 1s and 2s into ascending order.

Description:

Given input integer array arr, with only 0s, 1s and 2s in unsorted order, sort arr such as all 0s are at start of array followed by all 1s and then all 2s.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={0,1,2,0,1,2} 0,0,1,1,2,2
arr={2,2,2,1,1,1,0,0,0} 0,0,0,1,1,1,2,2,2
arr={1,0,2} 0,1,2

Pseudocode:

The java method should accept following input parameters: arr1 (int array).
Initialize 3 int variables cnt0, cnt1, cnt2 to 0.
Iterate through arr using a for loop using idx as loop variable:
If arr[idx]=0, increment cnt0.
If arr[idx]=1, increment cnt1.
If arr[idx]=2, increment cnt2.
After above loop ends you have counts of 0s, 1s and 2s in arr.
Now, iterate through arr using a for loop using idx as loop variable:
Fill first cnt0 indexes with 0s, fill next cnt1 indexes with 1s and last cnt2 indexes with 2s.
return arr, it is now sorted as 0s, 1s and 2s.

Code:

public int[] arraySort0s1s2s(int[] arr) throws Exception{
	int cnt0=0; int cnt1=0; int cnt2=0;
	for (int idx=0; idx < arr.length; idx++) {
		if (arr[idx]==0) cnt0++;
		if (arr[idx]==1) cnt1++;
		if (arr[idx]==2) cnt2++;
	}
	for (int idx=0; idx < arr.length; idx++) {
		if (idx < cnt0) {
			arr[idx]=0;
		}else if ((idx >= cnt0)&&(idx < cnt0+cnt1)) {
			arr[idx]=1;
		}else if ((idx >= cnt1)&&(idx < cnt0+cnt1+cnt2)) {
			arr[idx]=2;
		}
	}
	return arr;	
}

Click here to download and run code and test cases !