This algorithm could be used for problems where some specific items need to placed next to each other where duplicate items could exist. Or where items need to sorted according to a particular criteria and duplicate may/may not exist.
An example problem could be:
Students are asked to stand in non-decreasing order of heights for an annual photo.
Return the minimum number of students not standing in the right positions. (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.)
Example 1:
Input: [1,1,4,2,1,3] Output: 3 Explanation: Students with heights 4, 3 and the last 1 are not standing in the right positions.
Note:
1 <= heights.length <= 1001 <= heights[i] <= 100
My solution using counting sort algorithm:
class Solution {
public int heightChecker(int[] nums) {
//counting sort
int[] heights=new int[101]; //100 possible heights
for(int height :nums)
heights[height]++;
int currheight=0;
int count=0;
for(int i=0;i<nums.length;i++)
{
while(heights[currheight]==0)
currheight++;
if(nums[i]!=currheight)
count++;
heights[currheight]--;
}
return count;
}
}
Another problem of a similar type:
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library’s sort function for this problem.
Example:
Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2]
class Solution {
public void sortColors(int[] nums) {
int[] colors=new int[3]; //0,1,2
for(int i=0;i<nums.length;i++)
colors[nums[i]]++;
int currcolor=0;
int i=0;
while(i<nums.length)
{
if(colors[currcolor]!=0)
{
nums[i]=currcolor;
i++;
colors[currcolor]--;
}
else
{
currcolor++;
}
}
}
}