使用 BUbble 排序C++进行矢量排序

Vector sorting using BUbble sort C++

本文关键字:排序 C++ BUbble 使用      更新时间:2023-10-16

我需要一个简单的程序来接受字符串向量并使用气泡排序进行排序并显示结果。同时执行程序自动终止。

#include<bits/stdc++.h>
#include<iostream>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
vector<string> v2;
void Bsortchar(vector <string> &ch)
{
    int i, j;
    string temp[1][200];
    int charLength = ch.size();
    cout<<ch.size();
    for(i = 0; i <= charLength; i++)
    {
        for (j=0; j < (charLength -1); j++)
        {
            if (ch[j+1] < ch[j])
            {
                temp[1][200] = ch[j];
                ch[j] = ch[j+1];
                ch[j+1]= temp[1][200];
            }
        }
    }
    return;  
}
int main()
{
    int charSize;
    //**********************************************************
    cout<<"Enter the Size of the char Vector"<<endl;
    cin>>charSize;
    cout<<"Enter the char Vector"<<endl;
    string c;
    for(int i=0;i<=charSize;i++)
    {
        cout<<i<<":";
        getline(cin,c);
        v2.push_back(c);
    }
    //************************************************************
    Bsortchar(v2);
    //***********************************************************
    cout<<endl<<"The sorted character vector array is : "<<endl;
    for(int i=0;i<=charSize;i++)
    {
        cout<<v2[i]<<" ";
    }
    //***********************************************************
    return 0;
}

需要接受来自用户的字符串,并在执行气泡排序后显示结果。

您有未定义的行为temp[1][200]并且超出了这个(免费(二维数组的两个部分的末端。

这里不需要数组,只需要一个临时数组。

auto temp = ch[j];
ch[j] = ch[j+1];
ch[j+1]= temp;

或者,最好可以使用现有函数

std::swap(ch[j], ch[j+i]);