来求教!用快速排序排一个结构数组,帮忙看一下我的程序吧!
大概就是输入n(<100000)个人的数据(名字、国家、财富),排出财富前m(<100)个人,并将财富按从大到小将每个人输出。我的程序编译貌似没问题,就运行的时候,输入第二个人的数据时就程序出问题。T T高人们帮我看一下啊...要怎么改?有什么要改进的地方也说一下啊!#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Error( Str ) FatalError( Str )
#define FatalError( Str ) fprintf( stderr, "%s\n", Str ), exit( 1 )
#define MaxN 100000
#define MaxM 100
#define Cutoff ( 3 )
typedef struct people_list *PtrToList;
typedef PtrToList Person;
struct people_list{
char name[20];
char country[20];
int money;
};
typedef int ElementType;
void InsertionSort( Person A[ ], int N );
void Swap(Person A, Person B);
ElementType Median3( Person A[ ], int Left, int Right );
void Qsort( Person A[], int Left, int Right );
int main(void){
int n,m,i,j;
printf("enter N and M:");
scanf("%d%d",&n,&m);
Person people[MaxN];
printf("Enter name, nationality and wealth:\n");
for(i=0;i<n;i++){
scanf("%s%s%d",people[i]->name,people[i]->country,&people[i]->money);
}
Qsort(people,0,n-1);
for(j=n-1;j>=n-m;j--){
printf("%s %s %d\n",people[j]->name,people[j]->country,people[j]->money);
}
return 0;
}
void Swap( Person A, Person B )
{
Person Tmp;
Tmp=A;
A=B;
B=Tmp;
}
void InsertionSort( Person A[ ], int N )
{
int j, P;
Person Tmp;
for( P = 1; P < N; P++ ) {
Tmp=A[P];
for( j = P; j > 0 && A[ j - 1 ]->money > Tmp->money; j-- )
A[ j ]= A[ j - 1 ];
A[ j ]= Tmp;
}
}
ElementType Median3( Person A[ ], int Left, int Right )
{
int Center = ( Left + Right ) / 2;
if( A[ Left ]->money > A[ Center ]->money )
Swap( A[ Left ], A[ Center ] );
if( A[ Left ]->money > A[ Right ]->money )
Swap( A[ Left ], A[ Right ]);
if( A[ Center ]->money > A[ Right ]->money )
Swap( A[ Center ], A[ Right ]);
Swap( A[ Center ], A[ Right - 1 ] ); /* Hide pivot */
return A[ Right - 1 ]->money;
}
#define Cutoff ( 3 )
void Qsort( Person A[],int Left, int Right )
{ int i, j;
ElementType Pivot;
if( Left + Cutoff <= Right ) {
Pivot = Median3( A, Left, Right );
i = Left; j = Right - 1;
for( ; ; ) {
while( A[ ++i ]->money < Pivot ){ }
while( A[ --j ]->money > Pivot ){ }
if( i < j )
Swap( A[ i ], A[ j ]);
else
break;
}
Swap( A[ i ], A[ Right - 1 ]); /* Restore pivot */
Qsort( A, i + 1, Right );
Qsort( A, Left, i - 1 );
}
else /* Do an insertion sort on the subarray */
Insertion Sort( A+Left, Right - Left + 1 );
}