retagged by
666 views
0 votes
0 votes
Given ‘N’ objects, which are coloured as red, white and blue. Sort these

objects so that objects of the same colour are adjacent, with the colours

in the order red, white and blue. Design an algorithm with a time com-

plexity of O(nlog n)
retagged by

1 Answer

3 votes
3 votes

Can be done in O(N) complexity, programmatically.

Considering an array is given where Red object is denoted as 0, White object is denoted as 1 and Blue object is denoted as 2.

Now, taking 3 variables count the number of 0s, 1s and 2s in each variable.

  • red_count = Number of 0s
  • white_count = Number of 1s
  • blue_count = Number of 2s

Then at last,

  • First assign ‘0’ red_count times in the array.
  • Then assign ‘1’ white_count times in the array.
  • Then assign ‘2’ blue_count times in the array.

Ex – 

Array = [1,0,1,2,0,1,2,1,2,0,1,2]

red_count = 3, white_count = 5, blue_count=4

Modified Array will be = [0,0,0,1,1,1,1,1,2,2,2,2].

Related questions

0 votes
0 votes
2 answers
2
_Madhuri asked Oct 9, 2021
661 views
The complexity of comparison based sorting algorithm is (nlogn) .How?
0 votes
0 votes
0 answers
3
0 votes
0 votes
2 answers
4
rahul sharma 5 asked Dec 8, 2017
1,031 views
Which of the following sorting techniques have best time complexity, if complexity is measured in terms of number of comparison? A Insertion sortB Selection sortC Merge s...