[InterviewBit] Sort by Color

Sort by Color

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void dnc(vector<int>& A, int l, int r) {
if(l == r) return;
int m = l + (r - l) / 2;
dnc(A,l,m);
dnc(A,m+1,r);
vector<int> now;
int i = l, j = m + 1;
while(i <= m and j <= r) {
if(A[i] < A[j]) now.push_back(A[i++]);
else now.push_back(A[j++]);
}
while(i <= m) now.push_back(A[i++]);
while(j <= r) now.push_back(A[j++]);
for(int i = l, j = 0; i <= r; i++,j++) {
A[i] = now[j];
}
}

void Solution::sortColors(vector<int> &A) {
dnc(A,0,A.size() - 1);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/26/PS/interviewbit/sort-by-color/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.