冒泡排序
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int a;
vector<int> vec;
for(int i=0;i<10;i++){
cin>>a;
vec.push_back(a);
}
for(int i=0;i<vec.size()-1;i++){
for(int j=0;j<vec.size()-1-i;j++){
if(vec[j]>vec[j+1]){
int temp=vec[j+1];
vec[j+1]=vec[j];
vec[j]=temp;
}
}
}
for(int i=0;i<vec.size();i++)
cout<<vec[i]<<" ";
cout<<endl;
return 0;
}
快速排序
#include <iostream>
#include <vector>
using namespace std;
int Partition(vector<int> &arr,int left,int right){
int i=left+1;
int j=right;
int temp=arr[left];
while(i<=j){
while(arr[i]<temp) i++;
while(arr[j]>temp) j--;
if(i<j) swap(arr[i++],arr[j--]);
else break;
}
swap(arr[j],arr[left]);
return j;
}
void quick_sort(vector<int> &arr,int left,int right){
if(left>=right) return;
int j=Partition(arr,left,right);
quick_sort(arr,left,j-1);
quick_sort(arr,j+1,right);
}
int main()
{
vector<int> arr;
int n,temp;
cin>>n;
for(int i=0;i<n;i++){
cin>>temp;
arr.push_back(temp);
}
quick_sort(arr,0,arr.size()-1);
for(int i=0;i<arr.size();i++)
cout<<arr[i]<<' ';
cout<<endl;
return 0;
}
归并排序
#include <iostream>
#include <vector>
using namespace std;
void Merge(vector<int> &arr,int low,int mid,int high){
int *help=new int(high-low+1);
int p1=low,p2=mid+1,i=0;
while(p1<=mid&&p2<=high){
help[i++]=arr[p1]>arr[p2] ? arr[p2++]:arr[p1++];
}
while(p1<=mid){
help[i++]=arr[p1++];
}
while(p2<=high){
help[i++]=arr[p2++];
}
for(int i=0;i<high-low+1;i++){
arr[low+i]=help[i];
}
delete []help;
}
void SortProcess(vector<int> &arr,int low,int high){
if(low>=high) return;
int mid=(low+high)/2;
SortProcess(arr,low,mid);
SortProcess(arr,mid+1,high);
Merge(arr,low,mid,high);
}
void MergeSort(vector<int> &arr,int low,int high){
if(arr.size()<2)
return;
SortProcess(arr,low,high);
}
int main()
{
vector<int> arr;
int n,temp;
cin>>n;
for(int i=0;i<n;i++){
cin>>temp;
arr.push_back(temp);
}
MergeSort(arr,0,arr.size()-1);
for(int i=0;i<arr.size();i++)
cout<<arr[i]<<' ';
cout<<endl;
return 0;
}