用sort进行排序

要使用STL其中的算法,需要#include sort(数组名+n1,数组名+n2) n1和n2都是int类型的表达式,可以包含变量 如果n1=0,则 + n1可以不写 将数组中下标范围为[n1,n2)的元素从小到大排序,下标为n2的元素不在排序区间内 用法一:对基本类型的数组从小到大排序

int a[] = {15,4,3,9,7,2,6};
sort(a,a+7); //对整个数组从小到大排序

int a[] = {15,4,3,9,7,2,6};
sort(a,a+3); // 结果:{3,4,15,9,7,2,6}

int a[] = {15,4,3,9,7,2,6};
sort(a+2,a+5); //结果:{15,4,3,7,9,2,6}

用法二:对元素类型为T的基本类型数组从大到小排序 sort(数组名+n1,数组名+n2,greater())

int a[] = {15,4,3,9,7,2,6};
sort(a+1,a+4,greater()); //结果:{15,9,4,3,7,2,6}

用法三:用自定义的排序规则,对任何类型T的数组排序 sort(数组名+n1,数组名+n2,排序规则结构名()) 排序规则结构的定义方式:

struct 结构名
{
bool operator()( const T & a1,const T & a2)
{
//若a1应该在a2前面,则返回true
//否则返回false。
}
};

#include
#include
#include
using namespace std;

struct Rule1 //按从大到小排序
{
bool operator()(const int & a1, const int & a2) {
return a1 > a2;
}
};
struct Rule2 //按个位数从小到大排序
{
bool operator()(const int & a1, const int & a2) {
return a1 % 10 < a2 % 10;
}
};

void Print(int a[], int size) {
for (int i = 0; i < size; ++i)
cout << a[i] << “,”;
cout << endl;
}

int main(){
int a[] = { 12,45,3,98,21,7 };
sort(a, a + sizeof(a) / sizeof(int)); //从小到大
cout << “1) “; Print(a, sizeof(a) / sizeof(int));
sort(a, a + sizeof(a) / sizeof(int), Rule1()); //从大到小
cout << “2) “; Print(a, sizeof(a) / sizeof(int));
sort(a, a + sizeof(a) / sizeof(int), Rule2()); //按个位数从小到大
cout << “3) “; Print(a, sizeof(a) / sizeof(int));
return 0;
}

输出结果: 1) 3,7,12,21,45,98, 2) 98,45,21,12,7,3, 3) 21,12,3,45,7,98,

用sort对结构数组进行排序

#include
#include
#include
using namespace std;

struct Student {
char name[20];
int id;
double gpa;
};

Student students [] = {
{“Jack”,112,3.4},{“Mary”,102,3.8},
{“Mary”,117,3.9}, {“Ala”,333,3.5},
{“Zero”,101,4.0}
};

struct StudentRule1 { //按姓名从小到大排
bool operator() (const Student & s1,const Student & s2) {
if(_stricmp(s1.name,s2.name) < 0)
return true;
return false;
}
};
struct StudentRule2 { //按id从小到大排
bool operator() (const Student & s1,const Student & s2) {
return s1.id < s2.id;
}
};
struct StudentRule3 {//按gpa从高到低排
bool operator() (const Student & s1,const Student & s2) {
return s1.gpa > s2.gpa;
}
};

void PrintStudents(Student s[], int size) {
for (int i = 0; i < size; ++i)
cout << “(“ << s[i].name << “,”
<< s[i].id << “,” << s[i].gpa << “) “;
cout << endl;
}

int main() {
int n = sizeof(students) / sizeof(Student);
sort(students, students + n, StudentRule1()); //按姓名从小到大排
PrintStudents(students,n);
sort(students,students+n,StudentRule2()); //按id从小到大排
PrintStudents(students,n);
sort(students,students+n,StudentRule3()); //按gpa从高到低排
PrintStudents(students,n);
return 0;
}

输出结果: (Ala,333,3.5) (Jack,112,3.4) (Mary,102,3.8) (Mary,117,3.9) (Zero,101,4) (Zero,101,4) (Mary,102,3.8) (Jack,112,3.4) (Mary,117,3.9) (Ala,333,3.5) (Zero,101,4) (Mary,117,3.9) (Mary,102,3.8) (Ala,333,3.5) (Jack,112,3.4)