标签:closed ble end names swap blank 快速 const opened
tips:
1.注意边界处理,避免出现死循环
/*
eg:2
1 2
用i则不能取到左边界,把x取值改成向上取整
用j则不能取到右边界,把x取值改成向下取整
取到边界会导致递归死循环
*/
#include<iostream>
#include<cstdio>
using namespace std;
const int N=1e6+10;
int n;
int q[N];
void quick_sort(int q[], int l, int r){
if(l>=r) return;
int x=q[l+r>>1],i=l-1,j=r+1;
while(i < j){
do i++; while(q[i]<x);
do j--; while(q[j]>x);
if(i<j) swap(q[i],q[j]);
}
//这里左半边排序不能改成我之前的模板(l,j-1),因为x的位置在每次拍完序后没有被固定
quick_sort(q,l,j);////用i要保证不用到q的左边界,x取值那也要调整。
quick_sort(q,j+1,r);
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&q[i]);
quick_sort(q,0,n-1);
for(int i=0;i<n;i++) printf("%d ",q[i]);
return 0;
}
//AcWing 787. 归并排序
//实现思路,完善细节。
#include<cstdio>
using namespace std;
const int N=1e5+10;
int n;
int q[N],tmp[N];
void merge_sort(int q[],int l, int r){
if(l>=r) return;
int mid=l+r>>1;
merge_sort(q,l,mid);
merge_sort(q,mid+1,r);
int i=l,j=mid+1;
int k=0;
while(i<=mid && j<=r){
if(q[i]<=q[j]) tmp[k++]=q[i++];
else tmp[k++]=q[j++];
}
while(i<=mid) tmp[k++]=q[i++];
while(j<=r) tmp[k++]=q[j++];
for(int i=l,j=0; i<=r; i++,j++) q[i]=tmp[j];
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&q[i]);
merge_sort(q,0,n-1);
for(int i=0; i<n; i++) printf("%d ",q[i]);
return 0;
}
//关键是定义性质,二分出这个性质的边界
//mid=(l+r+1)/2是因为向下取整,若l=r-1,则出现死循环
#include<iostream>
#include<cstdio>
using namespace std;
int n,m;
const int N=100010;
int q[N];
int main(){
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) scanf("%d",&q[i]);
while(m--){
int x;
scanf("%d",&x);
int l=0,r=n-1;
while(l<r){
int mid=l+r>>1;
if(q[mid]>=x) r=mid;
else l=mid+1;
}
if(q[l]!=x) cout<<"-1 -1"<<endl;
else{
cout<<l<<‘ ‘;
int l=0,r=n-1;
while(l<r){
int mid=l+r+1>>1;
if(q[mid]<=x) l=mid;
else r=mid-1;
}
cout<<r<<endl;
}
}
return 0;
}
标签:closed ble end names swap blank 快速 const opened
原文地址:https://www.cnblogs.com/SUMaywlx/p/12301012.html