结构体快排回顾(sort)

一般来说,我做竞赛的时候排序一般用快排

很快很方便

普通sort(从小到大)

sort(a,a+n);

直接贴一段代码吧,包含了vector,sort,结构体等简单东西综合

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct example
{
    int elem1;
    int elem2;
}example;

/*这个comparison函数很重要.如果希望升序排序,就是"<",降序排列就是">"号,这样便于直观记忆.如果希望用elem2作为比较标准
就把elem1改为elem2,这样结构体就以elem2为比较标准排序了.*/
bool comparison(example a,example b){
    return a.elem1<b.elem1;
}

int main()
{
    int N;
    fin>>N;

    vector<example> array(N);

    for(int i=0;i<N;i++)
    {
        fin>>array[i].elem1>>array[i].elem2;
    }

    sort(array.begin(),array.end(),comparison);

    for(int i=0;i<N;i++)
    {
        cout<<array[i].elem1<<" "<<array[i].elem2<<endl;
    }
        return 0;
}

  

再搞一段

#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;

typedef struct index 
{
	int a,b;
}index;

bool cmp(index a , index b)
{
	if (a.a > b.a )
	{
		return true;
	}
	else
		if ( a.a == b.a  )
		{
			if (a.b > b.b )
			{
				return true ;
			}
		}
	return false ;
}

int main()
{
	index c[100];
	srand( time(0) );
	for (int i = 0 ; i < 100 ; ++i )
	{
		c[i].a = rand()%10 ; 
		c[i].b = rand()%10 ;
	}

	sort( c , c+100 , cmp );


	for (i = 0 ; i < 100 ; ++i )
	{
		cout<<c[i].a <<"   "<<c[i].b <<endl;
	}
	return 0;
}

  

posted @ 2016-11-22 19:09  zach96  阅读(1343)  评论(0编辑  收藏  举报