代码
#include <iostream>
#include <algorithm>
#include <string>
#include <assert.h>
using namespace std;
char** GetStrArr(int nArr[],int nLen)
{
assert(nArr && nLen > 0);
char** strArr = new char*[nLen];
for (int i = 0;i < nLen;i++)
{
char* str = new char[10];//假设最大数字长度为9
strArr[i] = itoa(nArr[i],str,10);
}
return strArr;
}
void Print(char** strArr,int nLen)
{
assert(strArr && nLen > 0);
for (int i = 0;i < nLen;i++)
{
cout<<strArr[i]<<" ";
}
cout<<endl;
}
bool Cmp(char* strFirst,char* strSec)
{
assert(strFirst && strSec);
string strF(strFirst);
string strS(strSec);
string strFS = strF + strS;
string StrSF = strS + strF;
return strFS < StrSF;
}
void MinNum(int nArr[],int nLen)
{
char** strArr = GetStrArr(nArr,nLen);
sort(strArr,strArr + nLen,Cmp);
Print(strArr,nLen);
}
int main()
{
//int nArr[3] = {3,32,321}; //321 32 3
//int nArr[3] = {4,32,321}; //321 32 4
//int nArr[4] = {4589,101,41425,9999};//101 41425 4589 9999
//int nArr[11] = {1234,123,120,11,1540,234,32,321,322,323,324};
//输出:11 120 123 1234 1540 234 321 322 32 323 324
//int nArr[2] = {1234,123}; //123 1234
//int nArr[2] = {323234,32}; //32 323234
//int nArr[2] = {323231,32}; //323231 32
//int nArr[2] = {323232,32}; //323232 32
int nArr[2] = {323232,323232}; //323232 323232
MinNum(nArr,2);
system("pause");
return 1;
}
代码
#include <iostream>
#include <algorithm>
#include <assert.h>
using namespace std;
char** GetStrArr(int nArr[],int nLen)
{
assert(nArr && nLen > 0);
char** strArr = new char*[nLen];
for (int i = 0;i < nLen;i++)
{
char* str = new char[10];//假设最大数字长度为9
strArr[i] = itoa(nArr[i],str,10);
}
return strArr;
}
void Print(char** strArr,int nLen)
{
assert(strArr && nLen > 0);
for (int i = 0;i < nLen;i++)
{
cout<<strArr[i]<<" ";
}
cout<<endl;
}
bool Cmp(char* strFirst,char* strSec)
{
assert(strFirst && strSec);
char* pCurF = strFirst;
char* pCurS = strSec;
char* pCur = NULL;
while(*pCurF && *pCurF == *pCurS)
{
pCurF++;
pCurS++;
}
//循环终止时,可能的情况:两字符都是0 + 两字符不等且全不为0 + 两字符不等且有一个为0
if (*pCurF == *pCurS) //两字符都是0
{
return false;
}
else
{
if (*pCurF == 0) //一个为0,一个不为0,
{
return Cmp(strFirst,pCurS);
}
else if (*pCurS == 0)
{
return Cmp(pCurF,strSec);
}
else
{
if (*pCurF > *pCurS)
{
return false; //第一个字符串大
}
else
{
return true;
}
}
}
}
void MinNum(int nArr[],int nLen)
{
char** strArr = GetStrArr(nArr,nLen);
sort(strArr,strArr + nLen,Cmp);
Print(strArr,nLen);
}
int main()
{
//int nArr[3] = {3,32,321}; //321 32 3
//int nArr[3] = {4,32,321}; //321 32 4
//int nArr[4] = {4589,101,41425,9999};//101 41425 4589 9999
//int nArr[11] = {1234,123,120,11,1540,234,32,321,322,323,324};
//输出:11 120 123 1234 1540 234 321 322 32 323 324
//int nArr[2] = {1234,123}; //123 1234
//int nArr[2] = {323234,32}; //32 323234
//int nArr[2] = {323231,32}; //323231 32
//int nArr[2] = {323232,32}; //323232 32
int nArr[2] = {323232,323232}; //323232 323232
MinNum(nArr,2);
system("pause");
return 1;
}