Предостережение: Большинство других респондентов указали на основные ошибки в вашем коде, но здесь есть некоторые более мелкие и некоторые упрощения.
Перед выполнением strcat
назад к tab
, мы должны сделать tab[0] = 0
, чтобы начальная 1009 * strcat
работала правильно.
Выполнение strcat(tab," ")
после того, что копирует слово, выходит за пределы конец tab
и, следовательно, неопределенное поведение. Также требуется ненужная очистка l oop для удаления лишнего пробела, которого не должно было быть в первую очередь.
Первоначальный «разбитый на слова» l oop можно [значительно] упростить.
Существуют некоторые стандартные ускорения для сортировки пузырьков
Я понимаю, что вы только начинаете [и некоторые школы действительно выступают за i
, j
и т. Д.], Но это лучше использовать несколько [более] различительных имен
В любом случае, вот несколько измененная версия:
#include <stdio.h>
#include <string.h>
int opt_dbg;
#define dbg(_fmt...) \
if (opt_dbg) \
printf(_fmt)
void
sort_alphabetically(char tab[])
{
char tmp[1001];
char words[501][1001];
char *src;
char *dst;
char *beg;
int chr;
int wordidx;
int wordcnt;
wordidx = 0;
dst = words[wordidx];
beg = dst;
// split up string into individual words
src = tab;
for (chr = *src++; chr != 0; chr = *src++) {
switch (chr) {
case ' ':
case '\t':
// wait until we've seen a non-white char before we start a new
// word
if (dst <= beg)
break;
// finish prior word
*dst = 0;
// point to start of next word
dst = words[++wordidx];
beg = dst;
break;
default:
*dst++ = chr;
break;
}
}
// finish last word
*dst = 0;
// get number of words
wordcnt = wordidx + 1;
if (opt_dbg) {
for (wordidx = 0; wordidx < wordcnt; ++wordidx)
dbg("SPLIT: '%s'\n",words[wordidx]);
}
// in bubble sort, after a given pass, the _last_ element is guaranteed to
// be the largest, so we don't need to examine it again
for (int passlim = wordcnt - 1; passlim >= 1; --passlim) {
int swapflg = 0;
// sorting words in alphabetical order
for (wordidx = 0; wordidx < passlim; ++wordidx) {
char *lhs = words[wordidx];
char *rhs = words[wordidx + 1];
if (strcmp(lhs,rhs) > 0) {
dbg("SWAP/%d: '%s' '%s'\n",passlim,lhs,rhs);
strcpy(tmp,lhs);
strcpy(lhs,rhs);
strcpy(rhs,tmp);
swapflg = 1;
}
}
// if nothing got swapped, we can stop early (i.e. everything is in
// sort)
if (! swapflg)
break;
}
// clear out destination so [first] strcat will work
tab[0] = 0;
// copy back words into original string
// adding the space as a _prefix_ before a word eliminates the need for a
// cleanup to remove the last space
for (wordidx = 0; wordidx < wordcnt; ++wordidx) {
dbg("SORTED: '%s'\n",words[wordidx]);
// adding spaces before each word
if (wordidx > 0)
strcat(tab, " ");
// copying to tab
strcat(tab,words[wordidx]);
}
}
int
main(int argc,char **argv)
{
char input[] = "If you are working on something that you really care"
" about you dont have to be pushed The vision pulls you Steve Jobs";
--argc;
++argv;
for (; argc > 0; --argc, ++argv) {
char *cp = *argv;
if (*cp != '-')
break;
switch (cp[1]) {
case 'd':
opt_dbg = ! opt_dbg;
break;
}
}
sort_alphabetically(input);
printf("%s\n", input);
return 0;
}