对任意类型的数组排序

 为啥WrongAnswer呢。。。

#include 
using namespace std;
struct A {
	int nouse1;
	int nouse2;
	int n;
};
// 在此处补充你的代码
void mysort(void *a,int n,int size,int (*f)(const void *p1,const void *p2))
{
	if(size==sizeof(A))
	{
		A *a1=(A*)a;
		A *a2=a1+1;
		
		for(int i=0;i0)
				{
					int itemp=a2->n;
					a2->n=a1->n;
					a1->n=itemp;
				}
				if(j==n-1)
				{
					a1=(A*)a;
					a2=a1+1;
				}
				else
				{
					a1=a1++;
					a2=a2++;
				}
			}
		}
	}
	else
	{
		int *a1=(int*)a;
		int *a2=a1+1;
		
		for(int i=0;i0)
				{
					int itemp=*a2;
					*a2=*a1;
					*a1=itemp;
				}
				if(j==n-1)
				{
					a1=(int*)a;
					a2=a1+1;
				}
				else
				{
					a1=a1++;
					a2=a2++;
				}
			}
		}
	}
}
//
int MyCompare1( const void * e1,const void * e2) 
{
	int * p1 = (int * ) e1;
	int * p2 = (int * ) e2;
	return * p1 - * p2;
}
int MyCompare2( const void * e1,const void * e2) 
{
	int * p1 = (int * ) e1;
	int * p2 = (int * ) e2;
	if( (* p1 %10) - (* p2 % 10))
		return (* p1 %10) - (* p2 % 10);
	else
		return * p1 - * p2;
}
int MyCompare3( const void * e1,const void * e2) 
{
	A * p1 = (A*) e1;
	A * p2 = (A*) e2;
	return p1->n - p2->n;
}
int a[20];
A b[20];
int main ()
{	
	int n,i=0;
	while(cin >> n) {
		for(int i = 0;i < n; ++i) {
			cin >> a[i];
			b[i].n = a[i];
		}
		mysort(a,n,sizeof(int),MyCompare1);
		for(i = 0;i < n; ++i) 
			cout << a[i] << "," ;
		cout << endl;
		mysort(a,n,sizeof(int),MyCompare2);
		for(i = 0;i < n; ++i) 
			cout << a[i] << "," ;
		cout << endl;
		mysort(b,n,sizeof(A),MyCompare3);
		for(i = 0;i < n; ++i) 
			cout << b[i].n << "," ;
		cout << endl;
	}
	return 0;
}

从https://www.cnblogs.com/VincentValentine/p/5677353.html找到一个厉害的代码,

int mysort(void* a, int n, int w, int(*compare)(const void* e1, const void* e2)) {
    char* s = (char*)a;
    for(int i=n-1; i>=0; --i)
        for(int j=0; j 0) {
                for(int k=0; k

 

你可能感兴趣的:(C++)