数据结构练习(30)把数组排成最小的数
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; }
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------