Untitled
unknown
plain_text
10 months ago
1.9 kB
17
Indexable
package ARRAYS;
import java.util.Arrays;
import java.util.Scanner;
public class SortArrOf012 {
/**
* This class Takes an array nums consisting of only 0, 1, or 2. Sort the array in non-decreasing order.
* The sorting must be done in-place, without making a copy of the original array.
*
* Input: nums = [1, 0, 2, 1, 0]
* Output: [0, 0, 1, 1, 2]
* Explanation:
*
* The nums array in sorted order has 2 zeroes, 2 ones and 1 two
* Input: nums = [0, 0, 1, 1, 1]
* Output: [0, 0, 1, 1, 1]
* Explanation:
*
* The nums array in sorted order has 2 zeroes, 3 ones and zero twos
* Input: nums = [1, 1, 2, 2, 1]
* Output:
* [1, 1, 1, 2, 2]
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("ENTER ARR SIZE -> ");
int size = sc.nextInt();
System.out.println("ENTER ARR -> ");
int [] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Sorted Arr -> " + Arrays.toString(sortElements(arr)));
}
public static int [] sortElements(int [] nums) {
int zeroCount = 0;
int oneCount = 0;
int twoCount = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
zeroCount++;
} else if (nums[i] == 1) {
oneCount++;
} else {
twoCount++;
}
}
int size = nums.length;
for (int i = 0; i < zeroCount; i++) {
nums[i] = 0;
}
for (int i = zeroCount; i < size - twoCount; i++) {
nums[i] = 1;
}
for (int i = size-twoCount; i < size; i++) {
nums[i] = 2;
}
return nums;
}
}
Editor is loading...
Leave a Comment