gpt4 book ai didi

c++ - 插入排序算法,我的代码有什么问题?

转载 作者:行者123 更新时间:2023-11-28 03:19:33 24 4
gpt4 key购买 nike

我正在尝试使用 InsertSort 算法输入存储在 vector 中的字符串。

我所做的是将一些字符串输入到 vector 中,然后我使用插入排序对 vector 进行排序。

但我不确定为什么它不起作用!谁能指出我正确的方向?

#include <iostream>
#include <cstring>
#include <vector>
#include <cstdlib>
using namespace std;

int main (){
vector <string> names; //vector to store
string input; //input is the variable of strings

cout<<"Input a list of names \n";
cout<<"To end the list type 'END'" <<endl;

while (true){
getline(cin, input);

if (input =="END")
break;

names.push_back(input); //push into vector names
}


//my insertsort starts here
string temp;
int i;
for (int j = 1; j < names.size(); j++){
i = j - 1;

while ((i>0) && (names[i]>names[j]) ) {

names[i+1] = names[i];

i=i-1;
}

names[i+1] = names[j];

}



for (unsigned int i = 0; i<names.size (); i++)
cout<<names[i]<<endl;
cout<<endl;
system("pause");
}

非常感谢

编辑:我将输入字符串,例如我将输入:

彼得苹果兔子

我想要的输出是,按字母顺序:

苹果彼得兔子

在示例输入的那一刻,我得到:彼得苹果兔子

编辑 3:

我的插入排序现在看起来像这样:

 string temp;
int i;
for (int j = 1; j < names.size(); j++){
i = j - 1;
temp = names[j];

while ((i>=0) && (names[i]>names[j]) ) {
names[i+1] = names[i];
i=i-1;
}

names[i+1] = temp;
}

最佳答案

你错过了一分:

 //You have to remember names[j] before while loop
//the variable temp is never used
temp = names[j];
while ((i>=0) && (names[i]>temp) ) {
names[i+1] = names[i];
i=i-1;
}
names[i+1] = temp;
// since names[j] was already been filled by other words during swapping

如果不需要使用插入排序,最好使用STL排序算法。

关于c++ - 插入排序算法,我的代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15863998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com