ベクトルに格納された文字列の入力に対して InsertSort アルゴリズムを試しています。
私がしていることは、いくつかの文字列をベクトルに入力することです。次に、挿入ソートを使用してベクトルをソートします。
しかし、なぜうまくいかないのかわかりません!誰かが私を正しい方向に向けることができますか?
#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");
}
本当にありがとう
編集:文字列を入力します。たとえば、次のように入力します。
ピーター・アップル・ラビット
そして、私の希望する出力は、アルファベット順に次のとおりです。
アップルピーターラビット
現時点で入力例を使用すると、次のようになります。 Peter Apple Rabbit
編集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;
}