大整数排序

xiaoxiao2021-02-28  23

题目描述:

对N个长度最长可达到1000的数进行排序

输入描述:

输入第一行为一个整数N,(1<=N<=100)。 接下来的N行每行有一个数,数的长度范围为1<=len<=1000。 每个数都是一个正数,并且保证不包含前缀零。

输出描述:

可能有多组测试数据,对于每组数据,将给出的N个数从小到大进行排序,输出排序后的结果,每个数占一行。

代码

#include<stdio.h> #include<stdlib.h> #include<string.h> class BigData //基础版 { public: int len; bool ops;//正负 char data[1002]; bool pureCompare(const char*a,int len1,const char*b,int len2)//纯粹比数值 第一个大于第二个返回true 否则 false { if(len1<len2) return false; else if(len1>len2) return true; else { for(int i=0;i<len1;i++) { if(a[i]!=b[i]) { if(a[i]>b[i]) return true; else return false; } } return false;//默认不考虑相等 } } BigData() { len=0; ops=true; data[0]=0; } BigData(char *str) { int i=0; ops=true; len=strlen(str); if(str[i]=='-') { ops=false; len--; i++; } for(;i<=len;i++) data[i]=str[i]; } bool operator <(const BigData & other ) { if(ops==false&&other.ops==true) return true; else if(ops==true&&other.ops==false) return false; else if(ops==false) return pureCompare(data,len,other.data,other.len); else return !pureCompare(data,len,other.data,other.len); } bool operator >(const BigData & other ) { if(ops==false&&other.ops==true) return false; else if(ops==true&&other.ops==false) return true; else if(ops==false) return !pureCompare(data,len,other.data,other.len); else return pureCompare(data,len,other.data,other.len); } BigData& operator =(const BigData &other)//为了确保最后一个'\0' { len=other.len; ops=other.ops; for(int i=0;i<=len;i++) data[i]=other.data[i]; return *this; } void Prin() { printf("%s\n",data); } }; void BubbleSort(BigData *a,int len) { BigData temp; for(int i=0;i<len-1;i++) { for(int j=0;j<len-i-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } } int main() { BigData * a; int n; char s[1002]={'\0'}; while(scanf("%d",&n)!=EOF) { a=(BigData*)malloc(sizeof(BigData)*n); for(int i=0;i<n;i++) { scanf("%s",&s); //printf("%s",s); a[i]=BigData(s); } BubbleSort(a,n); for(int i=0;i<n;i++) { a[i].Prin(); } } return 0; }

注:基础类设计较为麻烦。

转载请注明原文地址: https://www.6miu.com/read-2630511.html

最新回复(0)