看题意要选用有稳定性的排序算法,加上要保留一些字符位置,所以用冒泡。
因为要跳过非字母字符,交换对象总难确定是否是下一个,所以需要位置下标,标记符合条件可以被交换的下一个字符位置next;以及上一次交换停在哪last,方便下一次大循环i直接跳到符合条件的位置。
#include <iostream> #include <cctype> using namespace std; void sortAlpha(string s){ int N = s.length(); int last, next; for(int i = N - 1; i > 0; i = last){ last = 0; for(int j = 0; j < i ; j++){ if(isalpha(s[j])){ next = j + 1; while(!isalpha(s[next]) && next < i ) next ++; if(isalpha(s[next]) && tolower(s[j]) > tolower(s[next])){ char c = s[j]; s[j] = s[next]; s[next] = c; last = j; } } } } cout << s << endl; } int main() { string s; getline(cin, s); sortAlpha(s); return 0; } // 64 位输出请用 printf("%lld")