I’m trying to make a insert sort with strings. That’s my code below.
<code>#include <stdio.h>
#include <string.h>
#define MAXLINES 5
#define MAXLINEC 1000
int
main(void)
{
char lines[MAXLINES][MAXLINEC] = {
"abcd",
"fghijk",
"lmn",
"opqr",
"stuvwxyz",
};
int i, j;
char temp[MAXLINEC];
for (i=2; i<MAXLINES; ++i)
{
j = i - 1;
while (j>0 && strlen(lines[j]) > strlen (lines[i]))
{
strcpy(temp, lines[i]);
strcpy(lines[i], lines[j]);
strcpy(lines[j], temp);
j = j - 1;
}
}
for (i = 0; i<MAXLINES; ++i)
printf("%sn", lines[i]);
return 0;
}
</code>
<code>#include <stdio.h>
#include <string.h>
#define MAXLINES 5
#define MAXLINEC 1000
int
main(void)
{
char lines[MAXLINES][MAXLINEC] = {
"abcd",
"fghijk",
"lmn",
"opqr",
"stuvwxyz",
};
int i, j;
char temp[MAXLINEC];
for (i=2; i<MAXLINES; ++i)
{
j = i - 1;
while (j>0 && strlen(lines[j]) > strlen (lines[i]))
{
strcpy(temp, lines[i]);
strcpy(lines[i], lines[j]);
strcpy(lines[j], temp);
j = j - 1;
}
}
for (i = 0; i<MAXLINES; ++i)
printf("%sn", lines[i]);
return 0;
}
</code>
#include <stdio.h>
#include <string.h>
#define MAXLINES 5
#define MAXLINEC 1000
int
main(void)
{
char lines[MAXLINES][MAXLINEC] = {
"abcd",
"fghijk",
"lmn",
"opqr",
"stuvwxyz",
};
int i, j;
char temp[MAXLINEC];
for (i=2; i<MAXLINES; ++i)
{
j = i - 1;
while (j>0 && strlen(lines[j]) > strlen (lines[i]))
{
strcpy(temp, lines[i]);
strcpy(lines[i], lines[j]);
strcpy(lines[j], temp);
j = j - 1;
}
}
for (i = 0; i<MAXLINES; ++i)
printf("%sn", lines[i]);
return 0;
}
It compiled, the output is correct, but the first element isn’t in ordering. It was compiled with “cc -Wall -o main main.c”
enter image description here
New contributor
mis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.