class Solution {
public:
void sortColors(int A[], int n) {
int r = 0,p = 0,b = n - 1;
while(p <= b){
if(A[p] == 0){
Swap(A,p,r ++);
p ++;
}
else if(A[p] == 2)
Swap(A,p,b --);
else
p ++;
}
}
void Swap(int A[],int i,int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
};
网上看到的另类方法:平移插入
class Solution {
public:
void sortColors(int A[], int n) {
int i = -1;
int j = -1;
int k = -1;
for(int p = 0; p < n; p ++)
{
//根据第i个数字,挪动0~i-1串。
if(A[p] == 0)
{
A[++k] = 2; //2往后挪
A[++j] = 1; //1往后挪
A[++i] = 0; //0往后挪
}
else if(A[p] == 1)
{
A[++k] = 2;
A[++j] = 1;
}
else
A[++k] = 2;
}
}
};
本文介绍了一种新颖的算法,通过平移插入法实现彩色元素的快速排序,不仅适用于初学者理解,也为专业人士提供了优化排序过程的新视角。
1385

被折叠的 条评论
为什么被折叠?



