看了12期的讲解,赶紧回来把代码写出来:
开的VS2005写的,显得累赘。。。
找奇数次出现的元素所用的循环可以合并到后来的排序的循环里去的,不过那样,太丑。。。
刚看讲解时以为说的是选择成对字符时可以“左右开弓”?? 但做起来似乎代码很麻烦,所以干脆以左半边为准排序。
//
huiwen.cpp : Defines the entry point for the console application.
//
#include " stdafx.h "
void swap ( char * const s, int i, int j)
... {
char temp;
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
int pseudo_bubble ( char * const s, int length)
... {
int i,j,k;
int odd;
char alphabet[26];
int count=0;
for (i=0; i<length; i++)
alphabet[s[i]-'a']++;
odd = -1;
for (i=0; i<sizeof(alphabet); i++)
if (alphabet[i] % 2) ...{
if (odd = -1) // the first 'odd'
odd = 'a' + i;
else // 2 odds
return -1;
}
i=0;
while (s[i] != s[length-1-i]) ...{ // until the corresponding element is right
j = length-1-i;
for (k=j-1; k>i && s[k]!=s[i]; k--); // find the corresponding element's location
if (k == i) ...{// find nobody -> this is the last 'odd' - closest to the center
swap(s,k,k+1);
} else ...{
while (k<j) ...{
swap(s,k,k+1); // bubble it out
count++;
k++;
}
i++;
}
}
return count;
}
int _tmain( int argc, _TCHAR * argv[])
... {
int x;
char s[] = ...{'a','b','a','c','a','e','b','a','d','c','d'};
//{'a','b','a','c','a','b','a','d','c','d'};
//{'a','b','a','c','e','b','e','d','c','d'};
x = pseudo_bubble(s,sizeof(s));
if (x==-1)
printf("Impossible");
else
printf("%d",x);
//getchar();
return 0;
}
//
#include " stdafx.h "
void swap ( char * const s, int i, int j)
... {
char temp;
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
int pseudo_bubble ( char * const s, int length)
... {
int i,j,k;
int odd;
char alphabet[26];
int count=0;
for (i=0; i<length; i++)
alphabet[s[i]-'a']++;
odd = -1;
for (i=0; i<sizeof(alphabet); i++)
if (alphabet[i] % 2) ...{
if (odd = -1) // the first 'odd'
odd = 'a' + i;
else // 2 odds
return -1;
}
i=0;
while (s[i] != s[length-1-i]) ...{ // until the corresponding element is right
j = length-1-i;
for (k=j-1; k>i && s[k]!=s[i]; k--); // find the corresponding element's location
if (k == i) ...{// find nobody -> this is the last 'odd' - closest to the center
swap(s,k,k+1);
} else ...{
while (k<j) ...{
swap(s,k,k+1); // bubble it out
count++;
k++;
}
i++;
}
}
return count;
}
int _tmain( int argc, _TCHAR * argv[])
... {
int x;
char s[] = ...{'a','b','a','c','a','e','b','a','d','c','d'};
//{'a','b','a','c','a','b','a','d','c','d'};
//{'a','b','a','c','e','b','e','d','c','d'};
x = pseudo_bubble(s,sizeof(s));
if (x==-1)
printf("Impossible");
else
printf("%d",x);
//getchar();
return 0;
}
找奇数次出现的元素所用的循环可以合并到后来的排序的循环里去的,不过那样,太丑。。。
刚看讲解时以为说的是选择成对字符时可以“左右开弓”?? 但做起来似乎代码很麻烦,所以干脆以左半边为准排序。