Leetcode: Sort colors
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.
Address: https://oj.leetcode.com/problems/sort-colors/
Algorithm: the question must be traversed once. Since there are three elements in total, we can set two variables pos_red and pos_blue to indicate that the red elements are stored between 0 and the pos_red-1, respectively, pos_blue + 1 to n-1 stores blue elements. Code:
1 class Solution { 2 public: 3 void sortColors(int A[], int n) { 4 if(n <= 1 || !A) return; 5 int pos_red = 0; 6 int pos_blue = n-1; 7 for(int i = 0; i <= pos_blue; ){ 8 if(A[i] == 0){ 9 swap(A[i],A[pos_red]);10 ++pos_red;11 ++i;12 }else if(A[i] == 2){13 swap(A[i],A[pos_blue]);14 --pos_blue;15 }else{16 ++i;17 }18 }19 }20 void swap(int &a, int &b){21 int temp = a;22 a = b;23 b = temp;24 }25 };
Leetcode: Sort colors