题解 | #字符串排序#

https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584

采用冒泡算法,这是一个稳定的排序算法,需要注意,该算法把相邻的元素两两交换,但是由于题目中给出字符中有其他字符,需要跳过,因此最后的排序算法如下
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
void sort_str(string &str) {
  bool exchange = true;
  int sz = str.size();
  for (int i = 0; i < sz - 1 && exchange; i++) {
    exchange = false;
    int j = sz - 1;
    int k = j - 1;
    while (k >= i) {
        if(isalpha(str[k])){
          if (isalpha(str[j]) && tolower(str[k]) > tolower(str[j])) {
            swap(str[k], str[j]);
             exchange = true;
          }
          j = k;
        }
      k = k - 1;
    }
  }
}
int main() {
    string str;
    getline(cin,str);
    sort_str(str);
    cout<<str<<endl;
}


全部评论

相关推荐

昨天 11:53
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务