| 
 
 根据胡凡和曾磊老师的《算法笔记》学习记录  说实话,我真是第一次才知道c++还有这么简便的排序函数,相比于C语言,省去了大量代码。  
sort( )  使用方法:  
 
 sort(首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(非必填))  必须加上头文件:#include< algorithm >和using namespace std;  
  
举个栗子:  
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
	int book[5]={5, 4, 2, 8, 7};
	sort(book,book+5);
	int i;
	for(i=0;i<5;i++)
	{
		printf("%d ",book[i]);
	}
	return 0;
}
  
char型数组  
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
	char book[]={'A','L','B','Q'};
	sort(book,book+4);
	int i;
	for(i=0;i<4;i++)
	{
		printf("%c ",book[i]);
	}
	return 0;
}
  
我们上面的排序都是由小到大排序,然后我们可以使用cmp来自定义排序方式。  
#include<stdio.h>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
	return a>b;
}
int main()
{
	int book[ ]={5,2,0,1,3,1,4};
	sort(book,book+7,cmp);
	int i;
	for(i=0;i<7;i++)
	{
		printf("%d ",book[i]);
	}
	return 0;
}
  
char型数组  
#include<stdio.h>
#include<algorithm>
using namespace std;
bool cmp(char a,char b)
{
	return a>b;
}
int main()
{
	char book[]={'Q','S','A','Z','L'};
	sort(book,book+5,cmp);
	int i;
	for(i=0;i<5;i++)
	{
		printf("%c ",book[i]);
	}
	return 0;
}
  
结构体数组排序  
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node
{
	int x,y;	
}book[10];
bool cmp(node a,node b)
{
	return a.x>b.x;
}
int main()
{
	book[0].x=5;
	book[0].y=2;
	book[1].x=0;
	book[1].y=5;
	book[2].x=2;
	book[2].y=1;
	sort (book,book+3,cmp);
	int i;
	for(i=0;i<3;i++)
	{
		printf("%d %d \n",book[i].x,book[i].y);
	}
	return 0;
}
  
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node
{
	int x,y;	
}book[10];
bool cmp(node a,node b)
{
	if(a.x!=b.x)
	return a.x>b.x;
	else return a.y<b.y;
}
int main()
{
	book[0].x=5;
	book[0].y=2;
	book[1].x=0;
	book[1].y=5;
	book[2].x=2;
	book[2].y=1;
	sort (book,book+3,cmp);
	int i;
	for(i=0;i<3;i++)
	{
		printf("%d %d \n",book[i].x,book[i].y);
	}
	return 0;
 } 
  
简单记录,庆祝开学… 
                
                
                
        
    
 
 |