数组排序
#include<iostream>
using namespace std;
int main()
{
int a[110];
int n;
cin>>n;
for(int i = 0;i<n;i++)
{
cin>>a[i];
}
for(int i = 0;i<n-1;i++)
{
for(int j = 0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
for(int i = 0;i<n;i++)
{
cout<<a[i]<<" ";
}
}
数字和排序
#include<iostream>
using namespace std;
int main()
{
int a[110];
int n;
cin>>n;
for(int i = 0;i<n;i++)
{
int tmp;
cin>>tmp;
int sum = 0;
while(tmp!=0)
{
sum = sum+tmp%10;
tmp = tmp/10;
}
a[i] = sum;
}
for(int i = 0;i<n-1;i++)
{
for(int j = 0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
for(int i = 0;i<n;i++)
{
cout<<a[i]<<" ";
}
}
个位排序
#include<iostream>
using namespace std;
int main()
{
int a[110];
int n;
cin>>n;
for(int i = 0;i<n;i++)
{
cin>>a[i];
}
for(int i = 0;i<n-1;i++)
{
for(int j = 0;j<n-1-i;j++)
{
if(a[j]%10>a[j+1]%10)
{
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
else if(a[j]%10==a[j+1]%10)
{
if(a[j] > a[j+i])
{
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
}
for(int i = 0;i<n;i++)
{
cout<<a[i]<<" ";
}
}
奇偶排序
#include<iostream>
using namespace std;
int main()
{
int a[110];
int n = 10;
for(int i = 0;i<n;i++)
{
cin>>a[i];
}
for(int i =0;i<n-1;i++)
{
for(int j = 0;j<n-1-i;j++)
{
if(a[j]%2==0 && a[j+1]%2==1)
{
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
else if(a[j]%2==1 && a[j+1]%2==1)
{
if(a[j]<a[j+1])
{
int tmp =a[j];
a[j]=a[j+1];
a[j+1] = tmp;
}
}
else if(a[j]%2==0 && a[j+1]%2==0)
{
if(a[j]<a[j+1])
{
int tmp =a[j];
a[j]=a[j+1];
a[j+1] = tmp;
}
}
}
}
for(int i = 0;i<n;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
寻找第K大数
#include<iostream>
using namespace std;
int main()
{
int n,k,a[110]={0};
cin>>n>>k;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(a[j]<a[j+1])
{
int tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
}
}
}
cout<<a[k-1]<<" ";
return 0;
}