1.冒泡排序
#include<bits/stdc++.h>
using namespace std;
int a[100];
int main(){
int n;
bool flag;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n-1;i++){
flag=0;
for(int j=1;j<=n-i;j++){
if(a[j]>a[j+1])
swap(a[j],a[j+1]);
flag=1;
}
if(flag==0)break;
}
for(int i=1;i<=n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
2.选择排序
#include<bits/stdc++.h>
using namespace std;
int a[100];
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n-1;i++){
for(int j=i+1;j<=n;j++)
if(a[i]>a[j]) swap(a[i],a[j]);
}
for(int i=1;i<=n;i++){
cout<<a[i]<<" ";
}
return 0;
}
3.插入排序
#include<bits/stdc++.h>
using namespace std;
int a[10005];
int main(){
int n,i,k,j,temp;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
for(j=i-1;j>=1;j--){
if(a[j]<a[i]) break;
}
if(j!=i-1){
temp=a[i];
for(k=i-1;k>j;k--){
a[k+1]=a[k];
}
a[k+1]=temp;
}
}
for(i=1;i<=n;i++){
cout<<a[i]<<" ";
}
return 0;
}
4.计数排序(桶排序)
#include<bits/stdc++.h>
using namespace std;
int a[10005];
const int k=10001;
int main(){
int n,x;
cin>>n;
for(int i=1;i<=n;i++){
cin>>x;
a[x]++;
}
for(int i=0;i<k;i++)
for(int j=a[i];j>0;j--)
cout<<i<<" ";
return 0;
}
5.快速排序
#include<bits/stdc++.h>
using namespace std;
int part(int* r,int low,int hight)//划分函数
{
int i=low,j=hight,point=r[low];//
while (i < j)
{
while (i<j && r[j]>point)
{
j--;
}
if(i < j)
{
swap(r[i++],r[j]);
}
while (i < j && r[i] <=point)
{
i++;
}
if(i < j)
{
swap(r[i],r[j--]);
}
}
return i;
}
void Quicksort(int* r,int low,int hight)
{
int mid;
if (low < hight)
{
mid = part(r, low, hight);
Quicksort(r, low, hight);
Quicksort(r, mid+1, hight);
}
}
int main()
{
int a[10001];
int N;
cout <<"请输入要排序的数据的个数:"<<endl;
cin>>N;
cout<< "请输入要排序的数据:"<<endl;
for(int i=0;i<N;i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}