Description:
Given an arrayNObjects colored red, white or blue, sort them 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.
Solution:
STL sort is not allowed in this question. In fact, it is not required because the array in this question is composed of only numbers 0, 1 and 2. Therefore, an array B of the same size can be created, initialize all elements to 1 and traverse array A. If a [I] = 0, put it in front of array B. If a [I] = 1, put it at the end of array B. Below is the code for this question:
1 class Solution { 2 public: 3 void sortColors(int A[], int n) { 4 int *B = new int[n]; 5 for (int i = 0; i < n; ++i) {B[i] = 1;} 6 int start = 0; 7 int lback = n - 1; 8 for (int i = 0; i < n; ++i) { 9 if (A[i] == 0) {10 B[start++] = 0;11 }12 if (A[i] == 2) {13 B[lback--] = 2;14 }15 }16 for (int i = 0; i < n; ++i) {17 A[i] = B[i];18 }19 delete [] B;20 }21 };
[Leetcode] Sort colors