快速排序
#include#include#include#includeusing namespace std;const int N = 100000 + 11;int n;int q[N];void quick_sort(int q[],int l,int r){if(l>=r)return ;int i = l-1;int j = r+1;int x = q[(l+r)/2];while(i<j){doi++;while(q[i]<x);doj--;while(q[j]>x);if(i<j) swap(q[i],q[j]);}quick_sort(q,l,j);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;}
归并排序
#include #include #include #include using namespace std;const int N = 100000 + 11;int n;int q[N];int temp[N];void merge_sort(int q[],int l,int r){if(l>=r)return ;int mid = (l+r)/2;merge_sort(q,l,mid);merge_sort(q,mid+1,r);int k = 0;int i = l,j = mid+1;while(i<=mid && j<=r){if(q[i]<=q[j]){temp[k++] = q[i++];}else{temp[k++] = q[j++];}}while(i<=mid) temp[k++] = q[i++];while(j<=r) temp[k++] = q[j++];for(i=l,j=0;i<=r;i++,j++) q[i] = temp[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;}
整数二分
#include #include #include #include using namespace std;const int N = 100000 + 11;int n,k,q[N];int main(){scanf("%d%d", &n,&k);for (int i = 0; i < n; i ++ )scanf("%d",&q[i]);while(k--){int x = 0;scanf("%d",&x);int l = 0,r = n-1;while(l<r){int mid = (l+r)/2;if(q[mid]>=x) r = mid;elsel = mid+1;}if(q[l]!=x){printf("-1 -1\n");continue;}else{printf("%d ",l);}l = 0,r = n-1;while(l<r){int mid = (l+r+1)/2;if(q[mid]<=x) l = mid;elser = mid-1;}printf("%d\n",r);}return 0;}
浮点数二分
#include #include #include #include using namespace std;double n;int main(){scanf("%lf", &n);double l = -10000,r = 10000;while((r-l)>=1e-8){double mid = (l+r)/2;if((mid*mid*mid)>=n)r = mid;elsel = mid;// if((mid*mid*mid)<=n)l = mid;// elser = mid;}printf("%lf",l);return 0;}