奇偶排序的C++实现

题目

从文件读入一个字符串,对其进行奇偶排序,使字母都按顺序排列。
奇偶排序:每个奇数的字符开始,依次比较,若a[i-1]>a[i]或者a[i]>a[i+1]则交换;再从偶数的字符开始,如此循环往复,直至交换完毕。

代码

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

//交换两个字符的函数
void MySwap(char &s1,char &s2){
    char temp = s1;
    s1 = s2;
    s2 = temp;
}

int main(){

    ifstream is("/Users/.../test.txt");
    if (!is){
        cerr << "File cannot be opened!\n";
        exit(EXIT_FAILURE);
    }

    string str;
    bool flag1,flag2;

    is >> str;
    cout << "Before sorting:\n" << str << endl;

    do {
        flag1 = true;
        flag2 = true;

        //从奇数字符开始
        for (int i = 1; i < str.length() - 1; i += 2) {
            if (str[i] > str[i + 1]){
                MySwap(str[i],str[i + 1]);
                flag1 = false;
            }
        }

        //从偶数字符开始
        for (int j = 0; j < str.length() - 1; j += 2) {
            if (str[j] > str[j + 1]){
                MySwap(str[j],str[j + 1]);
                flag2 = false;
            }
        }
    } while(flag1 == false || flag2 == false);
    //只有当两轮遍历结束后flag1与flag2都为true才跳出循环

    cout << "\nAfter sorting:\n" << str << endl;

    return 0;
}

测试结果如下所示

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_32925781/article/details/79559383