输入一个正整数数组,将它们连接起来排成一个数,输出能排出的所有数字中最小的一个。
* 例如输入数组{32,321},则输出这两个能排成的最小数32132
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 32
void pr_strs(char s[][MAXLEN], int len)
{
int i = 0;
for (i = 0; i < len; i++)
{
printf("%s\n", s[i]);
}
}
void swap_s(char* pLeft, char* pRight)
{
char tmp[MAXLEN];
strcpy(tmp, pLeft);
strcpy(pLeft, pRight);
strcpy(pRight, tmp);
}
//把两个数相互组合一下,再比较,不就知道谁最大了?
int compare_s(char* s1, char *s2)
{
char Ltmp[2*MAXLEN], Rtmp[2*MAXLEN];
strcpy(Ltmp, s1);
strcat(Ltmp, s2);
strcpy(Rtmp, s2);
strcat(Rtmp, s1);
return strcmp(Ltmp, Rtmp);
}
//快速排序
void qs_s(char a[][MAXLEN], int begin, int end)
{
char c[MAXLEN];
int left = begin, right = end;
strcpy(c, a[begin]);
if (left > right)
return;
while (left < right)
{
while ((left < right) && compare_s(a[right], c) >= 0)
right--;
swap_s(a[left], a[right]);
while ((left < right) && (compare_s(a[left], c) < 0))
left++;
swap_s(a[right], a[left]);
}
strcpy(a[right], a[left]);
qs_s(a, begin, right - 1);
qs_s(a, right + 1, end);
}
int main(void)
{
char strs[][MAXLEN] ={ "23215", "1", "65" , "122", "1212", "1203", "140", "452", "321",
"312", "642", "4", "45","120", "451", "143", "3", "453", "4123", "6", "64",
"644","444"};
int len = sizeof(strs) / (sizeof(char) * MAXLEN);
pr_strs(strs, len);
qs_s(strs, 0, len - 1);
/* printf("\ncmp:%d\n", compare_s(strs[3], strs[4]));*/
printf("\nsort result:\n");
pr_strs(strs, len);
return 0;
}
排好序了就OK了。