在学会了一堆没用的算法之后,我写了人生中第一个快速排序和归并排序,你敢信?
#include <bits/stdc++.h>
using namespace std;
typedef int LL;
const LL maxn = 100000 + 100;
LL a[maxn],b[maxn];
void mergesort( LL l,LL r ){
if( l >= r ) return;
LL mid = l + r >> 1;
mergesort( l,mid );
mergesort( mid+1,r );
LL ll = l,rr = mid+1;
LL cnt = 0;
while( ll <= mid && rr <= r ){
if( a[ll] <= a[rr] ){
b[++cnt] = a[ll];
ll++;
}else{
b[++cnt] = a[rr];
rr++;
}
}
while( ll <= mid ) b[++cnt] = a[ll++];
while( rr <= r ) b[++cnt] = a[rr++];
for( LL i = l;i <= r;i++ ){
a[i] = b[1+i-l];
}
}
int main()
{
LL n;
scanf("%d",&n);
for( LL i = 1;i <= n;i++ ){
scanf("%d",&a[i]);
}
mergesort( 1,n );
for( LL i = 1;i <= n;i++ ){
printf("%d ",a[i]);
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
typedef int LL;
const LL maxn = 100000 + 10;
LL a[maxn];
inline void Qsort(int l,int r)
{
int i=l,j=r,mid=a[l] + a[r] >> 1;
while(i<=j)
{
while(a[i]<mid) i++;
while(a[j]>mid) j--;
if(i<=j)
{
swap(a[i],a[j]);
i++,j--;
}
}
if(l<j) Qsort(l,j);
if(i<r) Qsort(i,r);
}
int main()
{
LL n;
scanf("%d",&n);
for( LL i = 1;i <= n;i++ ) scanf("%d",&a[i]);
Qsort( 1,n );
for( LL i = 1;i < n;i++ ){
printf("%d ",a[i]);
}
printf("%d\n",a[n]);
return 0;
}
快速排序是最难的双指针了我认为,其实每次只需要把区间划分成两块且两块都不为空即可。怎末做到呢?选的划分值只要在待排序数组的值域闭区间之内就行,为什末呢。我们可以证明,只要执行了while循环中if语句,那末两块就不会同时为空。为什末一定会停呢,因为在划分值那一定会停一下,而且假设只有一个划分值,那末这两个指针在第一次停下之前一定不会交叉。