您的位置:首页 > 理论基础 > 数据结构算法

数据结构练习(30)把数组排成最小的数

2012-12-17 22:44 288 查看
http://zhedahht.blog.163.com/blog/static/25411174200952174133707/

思路:

首先想到的应该是要把数字排序,经过简单的分析即可以得出如何自己定制compare函数。

作者博客里面的compare力求精简而忽略了效率,如果自己写的话应该能快不少。

#include <cstdio>
#include <cstring>
#include <cstdlib>

const int MAXN = 10;

int mycompare(const void* s1, const void* s2)
{
char combine1[MAXN+1], combine2[MAXN+1];

strcpy(combine1, *(const char**)s1);
strcat(combine1, *(const char**)s2);

strcpy(combine2, *(const char**)s2);
strcat(combine2, *(const char**)s1);

return strcmp(combine1, combine2);
}

void PrintMinNumber(int n[], int len)
{
if (n == nullptr || len <= 0)
return ;

char** szn = (char**)(new int[len]);
for (int i = 0; i < len; ++i)
{
szn[i] = new char[MAXN];
sprintf(szn[i], "%d", n[i]);
}
qsort(szn, len, sizeof(char*), mycompare);

for (int i = 0; i < len; ++i)
printf("%s", szn[i]);
printf("\n");

for (int i = 0; i < len; ++i)
delete[] szn[i];
delete[] szn;
}

int main()
{
int n[10] = {32, 321};
PrintMinNumber(n, 2);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐