插入排序算法(我的实现,我不知道该脚本的官方脚本是什么)基于字符串的长度对字符串进行排序大多数字符串是按顺序排序的,但最后会以随机的Ascii字符打印1或2(或者不是在末尾打印)所有)
#include <stdio.h>
#include <stdlib.h>
main()
{
int i,j,N;
printf("\nInput amount of strings ");
scanf("%d",&N);
fflush(stdin);
{
int min;
char *swap=(char*)malloc(sizeof(char)*150);
char *A[N],**temp;
for(i=0;i<N;i++)
*(A+i)=(char*)malloc(N*sizeof(char));
temp=A;
for(i=0;i<N;i++){
printf("\nInput %d element:",i+1);
fgets(*(temp+i),150,stdin);
}
printf("\n\n----------------------------------\n");
for(i=0;i<N;i++)
printf("%s",A[i]);
printf("----------------------------------\n\n");
//insertion sort
for(i=0;i<N;i++){
min=i;//current is min
for(j=i+1;j<N;j++){
//Compare assumingly min with all next
if((strcmp(A[j],A[min]))<0){
min=j;
}
//Next min found?
} //Swap
if(min!=i){
swap=A[i];
A[i]=A[min];
A[min]=swap;
}
}
free(swap);
printf("\n After insertion point\n");
printf("\n----------------------------------\n");
for(i=0;i<N;i++)
printf("%s",A[i]);
printf("----------------------------------");
}
return 0;
}
最佳答案
意外的空白可能是因为数组“ A”的第一个元素为空字符串。
scanf()读取所有字符,但将'\ n'(换行符)保留在stdin中,该值由您首先读取的fgets()并保存为数组“ A”中的第一个条目。
改变这个
int i,j,N;
printf("\nInput amount of strings ");
scanf("%d",&N);
对此
int i,j,N;
char temp;
printf("\nInput amount of strings ");
scanf("%d%c",&N,&temp);
这将从标准输入中删除尾随的换行符,并让您正确保存第一个元素。这可能是导致您遇到问题的原因。
关于c - 基于长度的字符串排序算法(不打印所有结果正确)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21209889/