"Programming Thinking and Practice" 1032. Sorting of row data
topic
train of thought
Similar to the strcmp function of strings, just write the sorting function as required.
The key lies in how to process the input data. Since there are at most 50 data in a row (excluding 1), you can open an array with a size of 51 and initialize it to -1, but store the data in the array when it is not -1.
Data size does not exceed 1 0 9 10^9109 , you can save it with int.
the code
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
int cmp(const void *a,const void *b)
{
int *m=(int*)a;
int *n=(int*)b;
int i;
while(*m!=-1&&*n!=-1)
{
if(*m!=*n)
{
return *n-*m; //从大到小
}
else{
n++;
m++;
}
}
if(*n==-1&&*m!=-1)
{
return -1;
}
else
{
return 1;
}
}
int main()
{
int T;
scanf("%d",&T);
for(int i=0;i<T;i++)
{
int N;
scanf("%d",&N);
int tab[N][51]; //预留一个-1的位置
for(int j=0;j<N;j++)
{
for(int k=0;k<51;k++)
{
tab[j][k]=-1;
}
}
for(int j=0;j<N;j++)
{
int k=0;
int temp;
while(scanf("%d",&temp)&&temp!=-1)
{
tab[j][k++]=temp;
}
}
qsort(tab,N,51*sizeof(int),cmp);
for(int j=0;j<N;j++)
{
for(int k=0;tab[j][k]!=-1;k++)
{
printf("%d ",tab[j][k]);
}
printf("\n");
}
}
return 0;
}