Candy Man
Candy Man

Reputation: 219

InsertionSort Algorithm, Whats Wrong with my Code?

I'm trying out a InsertSort Algorithm for an input of strings stored in a vector.

What I do is to input some strings into the vector, Then i use insertionsort to sort the vectors.

But I'm not sure why does it not work! Could anyone point me to the right direction?

#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");
}

Thanks a bunch

EDIT: I will be inputing strings for example I will type:

Peter Apple Rabbit

And my desired output is, in alphabatical order,:

Apple Peter Rabbit

At the moment with the example input, I get: Peter Apple Rabbit

EDIT 3:

My insert sort now looks like this:

 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;
    }

Upvotes: 0

Views: 145

Answers (1)

taocp
taocp

Reputation: 23624

You missed one point:

 //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

If it is not required to use insertion sort, you'd better use stl sort algorithm.

Upvotes: 2

Related Questions