Open In App

Sorting objects using In-Place sorting algorithm

Last Updated : 01 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of red, blue and yellow objects, the task is to use an in-place sorting algorithm to sort the array in such a way that all the blue objects appear before all the red objects and all the red objects appear before all the yellow objects.
Examples: 
 

Input: arr[] = {"blue", "red", "yellow", "blue", "yellow"} 
Output: blue blue red yellow yellow
Input: arr[] = {"red", "blue", "red", "yellow", "blue"} 
Output: blue blue red red yellow 
 


 


Approach: First of all map the values of blue, red and yellow objects to 1, 2 and 3 respectively using a hash table. Now use these mapped values whenever a comparison of two objects is required. So, the algorithm will sort the array of objects such that all blue objects ( mapping to value 1 ) will appear first, then all red objects ( mapping to value 2 ) and then all yellow objects ( mapping to value 3 ).
Below is the implementation of the above approach: 
 

C++
Java Python3 C# JavaScript

Output: 
blue blue red red yellow

 

Time complexity: O(n^2) since using quicksort

Auxiliary space: O(n) because using hash table 


Next Article

Similar Reads