
There’s in no way like a little debacle for sorting things out!!
Technical rounds are a crucial part of any interview or hiring process of a big tech company. Whether it is Amazon, Google, Capgemini, Flipkart or Accenture, you will always have to go through a technical round.
Well, to be honest, that’s the deciding round! So, the buildup is necessary.
But we are not only here to scare you. We have got your back and have come up with a solution to an advanced problem that you may commonly encounter in your interview. How to sort 012 in an array is one of the common problems that you will encounter in your interview and we have come up with a detailed solution for you.
Here, we are going to discuss different approaches that you can use to sort 0s 1s and 2s in an array in detail.
So, let’s get started with this guide.
Problem Statement:
Before learning any solutions or any other key takeaways, let’s understand what the problem is.
You will be given array A[] consisting of 0, 1, and 2 and no other elements. You will have to write a code to sort the given array in the ascending form.
To understand the problem in a better way, consider the following problem:
A= {1, 2, 0, 0, 1, 2, 0, 1, 2}
After sorting 0 1 and 2, the given array will look like this:
A= {0, 0, 0, 1, 1, 1, 2, 2, 2}
So, with the given example, you must be aware of how to sort 0 1 2 in an array. Let’s discuss how this sorting is done.
Ways To Sort 0 1 2 In An Array
To sort 0s, 1s and 2s in an array, you can use the following two ways:
Method 1: Brute Force Method
Method 2: Use a single traversal Method
Let’s discuss the following methods in detail.
Method 1: Brute Force Method
The brute force method uses double traversal to sort 0 1 2 in ascending order. However, it completely depends on the programmer to sort the elements in descending or ascending order.
Here is the algorithm that you will have to follow to sort 0s 1s and 2s in an array using the brute force method:
Begin with initializing an array of size N. Make sure that all its elements are in the form 0, 1 and 2.
Declare a function that you will use to sort the given array.
Mention elements of the given array as arguments in the function.
Now, in the function created, you will have to declare 3 variables: one-count, zero counts, and two-count.
Comments