编程笔记 cha 2-1 排序
排序算法
1. 排序(牛客网)
#include
#include
using namespace std;
void bubbleSort(int a[],int n){
int t;
for (int i=0;i<n-1;i++){
for (int j=0;j<n-i-1;j++){
if (a[j]>a[j+1]){
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
}
void selectSort(int a[],int n){
int k,t;
for (int i=0;i<n-1;i++){
k = i;
for (int j=i+1;j<n;j++){
if (a[j]<a[k]){
k = j;
}
}
if (k!=i){
t = a[k];
a[k] = a[i];
a[i] = t;
}
}
}
void Qsort(int a[],int low,int high){
if (low >= high)
return;
int first = low ;
int last = high ;
int key = a[first];
while (first < last){
while (first < last && a[last] >= key){
--last;
}
a[first] = a[last];
while (first < last && a[first] <= key){
++first;
}
a[last] = a[first];
}
a[first]=key;
Qsort(a,low,first-1);
Qsort(a,first+1,high);
}
bool cmp(int x,int y){
return x>y;
}
void print(int a[],int n){
for (int i=0;i<n;i++)
cout << a[i] << ' ';
cout<<endl;
}
int main()
{
int n,a[101];
while (cin >> n){
for (int i=0;i<n;i++)
cin >> a[i];
Qsort(a,0,n-1);
print(a,n);
}
return 0;
}
2.成绩排序
#include
#include
#include
using namespace std;
struct Stu{
char name[100];
int age;
int grade;
};
bool cmp(Stu s1,Stu s2){
if (s1.grade != s2.grade)
return s1.grade < s2.grade;
int tmp = strcmp(s1.name,s2.name);
if (tmp != 0)
return tmp < 0;
return s1.age < s2.age;
}
void print(Stu s[],int n){
for (int i=0;i<n;i++)
cout << s[i].name << ' '<<s[i].age<<' '<<s[i].grade<<endl;
}
int main()
{
int n;
Stu s[1001];
while (cin >> n){
for (int i=0;i<n;i++)
cin >> s[i].name>>s[i].age>>s[i].grade;
sort(s,s+n,cmp);
print(s,n);
}
return 0;
}
特殊排序
#include
#include
#include
using namespace std;
void print(int a[],int n){
cout<<a[n-1]<<endl;
if (n!=1){
for (int i=0;i<n-2;i++)
cout << a[i] << ' ';
cout <<a[n-2]<<endl;
}
else{
cout<<-1<<endl;
}
}
int main()
{
int n,a[1001];
while (cin >> n){
for (int i=0;i<n;i++)
cin >> a[i];
sort(a,a+n);
print(a,n);
}
return 0;
}
EXCEL排序
#include
#include
#include
using namespace std;
struct Stu{
int number;
char name[8];
int grade;
}student[100000];
int c;
char *my_itoa(int n)
{
static char str[7];
int i;
for(i=0;i<6;i++)
str[i]='0';
str[7]='\0';
i=5;
while(n)
{
str[i--]=n%10 + '0';
n/=10;
}
return str;
}
bool cmp(Stu a,Stu b)
{
switch(c)
{
case 1:return a.number<b.number;
case 2:
if (strcmp(a.name,b.name)==0)
return a.number-b.number<0;
else
return strcmp(a.name,b.name)<=0;
case 3:
if (a.grade==b.grade)
return a.number<b.number;
else
return a.grade<=b.grade;
default:return 0;
}
}
字符串排序
#include
#include
#include
#include
using namespace std;
int main()
{
char str[200];
while (scanf("%s",str)!=EOF)
{
sort(str,str+strlen(str));
cout<<str<<endl;
}
return 0;
}