Sort Colors
LeetCode Problem #75 (Medium)
Problem Statement
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.
Testcase
Prerequisite Knowledge
Counting Sort
Counting Sort is a sorting algorithm that is used to sort elements with duplicates in an array by counting the number of occurrences of each distinct element. An auxiliary array is used to store the count value of each unique element.
The sorting is performed by mapping the values in the auxiliary array as the index values of the distinct elements in the sorted output array.
Algorithm
Counting Sort Approach
In this approach, we use two auxiliary arrays to store the count of each element and to build the sorted array, using a calculation of the relative position of the first occurrence of each new element with respect to the position of the last occurrence of the previous element.
Initialize a counter array to store the count of each element and an output array to store the sorted elements.
Iterate through the original array and increment the count of each encountered element, while unseen element remain 0.
Change the count array to reflect the actual index of each element in the sorted array by adding the count of the previous element.
Build the output array by iterating through the length of the count array.
a. Store each element in the output array at the index determined by the index value of the element in the count array.
b. Decrement the count array.
Copy the output array to the original array.
Illustration
Consider the array [2, 1, 1, 2, 0].
We create a count array to store the number of times each element occurs in the original array.
We must change each index in the count array to reflect the actual index position that the elements would take in the output array by considering the number of times the previous element occurs and storing the new element at the index immediately after the last occurrence of the previous element.
Now, the count array contains the index value at which each element must be placed. Until a new index value is reached, the previous element's value will be repeated, thus effectively rendering that element the number of times that it has occurred in the original array.
Code
Last updated
Was this helpful?