Don't miss your Year-End Offer: Up to 20% OFF

Sort Array with Two Different Types of Integer Numbers

13 February 2024
public class HackerAlgo {

    public static void sortTwoTypes(int[] arr) {
        int count0 = 0;
        int count1 = 0;
        int n = arr.length;

        // Count the occurrences of 0 and 1
        for (int num : arr) {
            if (num == 0) {
                count0++;
            } else if (num == 1) {
                count1++;
            }
        }

        // Update the array with sorted values
        for (int i = 0; i< n; i++) {
            if (i< count0) {
arr[i] = 0;
            } else {
arr[i] = 1;
            }
        }
    }

    public static void main(String[] args) {
int[] exampleArr = {0, 1, 0, 1, 1, 0};
sortTwoTypes(exampleArr);
System.out.println(Arrays.toString(exampleArr
def sort_two_types(arr):
    count0 = arr.count(0)
    count1 = arr.count(1)

    # Update the array with sorted values
arr[:count0] = [0] * count0
arr[count0:] = [1] * count1

# Example usage
example_arr = [0, 1, 0, 1, 1, 0]
sort_two_types(example_arr)
print(example_arr)
#include <iostream>
#include <vector>

class HackerAlgo {
public:
    static void sortTwoTypes(std::vector<int>&arr) {
        int count0 = std::count(arr.begin(), arr.end(), 0);
        int count1 = std::count(arr.begin(), arr.end(), 1);

        // Update the array with sorted values
std::fill(arr.begin(), arr.begin() + count0, 0);
std::fill(arr.begin() + count0, arr.end(), 1);
    }
};

int main() {
    // Example usage
std::vector<int>exampleArr = {0, 1, 0, 1, 1, 0};
HackerAlgo::sortTwoTypes(exampleArr);
    for (int num :exampleArr) {
std::cout<<num<< " ";
    }
std::cout<< std::endl;

    return 0
class HackerAlgo {
    static sortTwoTypes(arr) {
const count0 = arr.filter(num =>num === 0).length;
const count1 = arr.filter(num =>num === 1).length;

        // Update the array with sorted values
arr.fill(0, 0, count0);
arr.fill(1, count0);

    }
}

// Example usage
constexampleArr = [0, 1, 0, 1, 1, 0];
HackerAlgo.sortTwoTypes(exampleArr);
console.log(exampleArr);

Leave a Comment