标签:style blog io color os for sp div log
1、三路划分
思想就是把相等的一段ignore
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<ctime> #include<iostream> #define maxn 21111111 using namespace std; int n, a[maxn]; void sort(int ll, int rr) { if (ll >= rr) return; int x = a[ll+rand()%(rr-ll+1)]; int i = ll, j = rr,p=ll,q=rr; while (i <= j) { while (a[i] < x) i++; while (x < a[j]) j--; if (i <= j) { swap(a[i], a[j]); if (a[i] == x) swap(a[p++], a[i]); if (i!=j && a[j] == x) swap(a[q--], a[j]); //i!=j重要 因为只要把相等的归在一边就可以了(左边) i++; j--; } } j = i - 1; //注意非常重要 因为有可能循环结束前i=j j __ i 所以要强行设置j=i-1 for (int k = ll; k < p; k++, j--) swap(a[k], a[j]); for (int k = rr; k>q; k--, i++) swap(a[k], a[i]); sort(ll, j); sort(i, rr); } int main() {
freopen("1.in","r",stdin);
freopen("1.out","w",stdout); srand(time(0)); scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); sort(0, n - 1); for (int i = 0; i < n; i++) printf("%d ", a[i]); printf("\n"); return 0; }
2、朴素快排
#include<ctime> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<iostream> #define maxn 21111111 using namespace std; int n,a[maxn]; void sort(int ll, int rr) { if (ll == rr) return; int key = a[rand() % (rr - ll + 1) + ll]; int i = ll,j = rr; while (i <= j) { while (a[i] < key) i++; while (a[j] > key) j--; if (i <= j) { swap(a[i], a[j]); i++; j--; } } if (ll < j) sort(ll, j); if (i < rr) sort(i, rr); } int main() { freopen("1.in","r",stdin); freopen("1.out","w",stdout); srand(time(0)); scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); sort(0, n - 1); for (int i = 0; i < n; i++) printf("%d ", a[i]); return 0; }
标签:style blog io color os for sp div log
原文地址:http://www.cnblogs.com/strawberryfgalois/p/4060505.html