遇到的問題是input很大的數字,然後ouput出這串數字所能組合出的最大數字,例如: 12, 34, 56要output: 563412
因為數字大所以我用array方式存數字,然後比較的話我想到透過qsort + strcmp的方式比較,function比較的扣長這樣:
int mycmp(const void *a, const void *b){
char const *aa = (char const *)a;
char const *bb = (char const *)b;
return strcmp(aa,bb);
}
main:
qsort(arr, n_nums, 1000, mycmp);
n是有幾個數字,
arr是二維陣列,
for(int i = 0; i < n; i++){
scanf("%s",&arr[i]);
}
但是我qsort完想印出結果arr完全是空的,也沒報錯,想請問各位大神是怎麼回事......
完整程式碼如下:(題目來自資工系朋友提供)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int mycmp(const void *a, const void *b){
//更改型別
char const *aa = (char const *)a;
char const *bb = (char const *)b;
//printf("cmp %s, %s\n",aa,bb);
return strcmp(aa,bb);
}
int main(){
int n;
char arr[12][1001];
while(scanf("%d", &n) != EOF){
for(int i = 0; i < n; i++){
scanf("%s",&arr[i]);
//printf("%d string is %s\n",i,arr[i]);
}
//use strcmp + qsort
qsort(arr, n, 1000, mycmp);
for(int i = 0; i < n; i++){
printf("%s",arr[i]);
}
printf("\n");
}
return 0;
}
謝謝!
$ ./a.out
3
1987
8765
3409
1987
3409
8765
3
1024
963
65
1024
65
963
^Z
[7]+ Stopped ./a.out
只改兩列qsort(arr, n, sizeof(arr[0]), mycmp);
和加一個換列printf("\n");
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int mycmp(const void *a, const void *b){
//更改型別
char const *aa = (char const *)a;
char const *bb = (char const *)b;
//printf("cmp %s, %s\n",aa,bb);
return strcmp(aa,bb);
}
int main(){
int n;
char arr[12][1001];
while(scanf("%d", &n) != EOF){
for(int i = 0; i < n; i++){
scanf("%s",&arr[i]);
//printf("%d string is %s\n",i,arr[i]);
}
//use strcmp + qsort
qsort(arr, n, sizeof(arr[0]), mycmp);
printf("\n");
for(int i = 0; i < n; i++){
printf("%s\n",arr[i]);
}
printf("\n");
}
return 0;
}