646 views

2 Answers

Best answer
4 votes
4 votes

Apply one pass to count a number of  $0, 1, 2$. Then in the second pass do filling $0$ first then $1$ then $2$.

So $O(n)$ time.

void sort(int arr[], int size)
{
    int count[3]; // count[0] for count number of 0's similarly count[1] for 1's and count[2] for 2's
    int i;
    
    for(i=0; i<size; i++) // O(n)
    {
        if (arr[i] == 0) count[0]++;
        else if (arr[i] == 1) count[1]++;
        else count[2]++;
    }
  
  i = 0;
  // insert element in sorted order
  while (count[0])
  {
      arr[i] = 0;
      count[0]--;
      i++;
  }
   while (count[1])
  {
      arr[i] = 1;
      count[1]--
      i++;
  }
   while (count[2])
  {
      arr[i] = 2;
      count[2]--;
      i++;
  }
}

 

selected by
0 votes
0 votes
...an array containing N elements and each element can either be 0 or 1 or 2 and in the question its mentioned that they want the best case time complexity, so can we assume that all the elements are 0’s or all the elements are 1’s or all elements are 2’s if soo then simply apply Insertion sort.

because in best case insetion sort takes o(n) time complexity because we just need to do n comparisons and no need of shift operation .

Related questions

2 votes
2 votes
1 answer
2
srestha asked Dec 22, 2016
851 views
Assume that A be an array of 16 elements. What is the difference between maximum number of inversion and minimum number of inversion for the array with 16 elements?
0 votes
0 votes
1 answer
3
Overflow04 asked Oct 20, 2022
508 views
What is the logic applied here.
0 votes
0 votes
1 answer
4
Prateek kumar asked Jan 16, 2017
396 views
shouldn't be the max size of array [ 2^n - 1] when the binary tree will be one side only.....and minimum "n" when it will be either full binary tree or complete binary tr...