排序
冒泡
#include<iostream> #include<algorithm> #include<cmath> using namespace std; const int N=100000; int n; int nums[N]; int main() { scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&nums[i]); for(int i=0;i<n;i++) { for(int j=0;j<i;j++) if(nums[j]>nums[j+1]) { swap(nums[j],nums[j+1]); } } for(int i=0;i<n-1;i++) cout<<nums[i]<<" "; cout<<nums[n-1]; cout<<endl; return 0; }
快速
#include<iostream> #include<cmath> #include<algorithm> using namespace std; long long *numbers; void quicksort(long long nums[],int left,int right) { if(left>=right) return; long long target=nums[left]; int i=left-1,j=right+1; while(i<j) { do i++; while(nums[i]<target); do j--; while(nums[j]>target); if(i<j) swap(nums[i],nums[j]); } quicksort(nums,left,j); quicksort(nums,j+1,right); } int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin>>n; numbers=new long long [n]; for(int i=0;i<n;i++) { cin>>numbers[i]; } quicksort(numbers,0,n-1); for(int i=0;i<n;i++) { cout<<numbers[i]<<" "; } delete numbers; return 0; }
归并
#include<iostream> #include<algorithm> #include<cmath> using namespace std; const int N=100000; int n; int nums[N],tmp[N]; void mergesort(int nums[],int left,int right) { if(left>=right) return; int mid=floor((left+right)/2); mergesort(nums,left,mid),mergesort(nums,mid+1,right); int k=0,p=left,q=mid+1; while(p<=mid&&q<=right) { if(nums[p]<=nums[q]) tmp[k++]=nums[p++]; else tmp[k++]=nums[q++]; } while(p<=mid) tmp[k++]=nums[p++]; while(q<=right) tmp[k++]=nums[q++]; for(int i=left,k=0;i<=right;i++,k++) nums[i]=tmp[k]; } int main() { scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&nums[i]); mergesort(nums,0,n-1); for(int i=0;i<n-1;i++) cout<<nums[i]<<" "; cout<<nums[n-1]; cout<<endl; return 0; }