2 Replies - 472 Views - Last Post: 27 May 2012 - 12:02 AM Rate Topic: -----

#1 indyarocks  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 104
  • Joined: 07-March 12

what's wrong with this alphabetical sorting of string ?

Posted 26 May 2012 - 10:45 PM

Hi,

I'm trying to write a program, which will sort a string (defined from 'a' to 'z') in alphabetical order. But its giving unexpected results.

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

string sorted(string str)
{
    int i,j;
    int size = str.size();
    for(i = 1; i < size ; i++ )
    {
        char temp = str[i];
        for(/*j = i*/ j = i-1; j >= 0 && str[j] > temp; j-- ) // Corrected.
        {
               // str[j] = str[j+1]; <<-- EDIT::Corrected.
               str[j+1] = str[j];
        }
        str[j+1] = temp;
    }
    return str;
}
int main()
{
    string str;
    cout << "Enter the string to sort" << endl;
    getline(cin,str);
    cout << "Sorted String: " << sorted(str) << endl;
    return 0;
}


Output:
Enter the string to sort
helo
Sorted String: heee

Process returned 0 (0x0)   execution time : 2.942 s
Press any key to continue.



Can anyone please point out my mistake ?
EDIT::Corrected the mistake in my code.
Now the output is :
Enter the string to sort
hello
Sorted String: ehllo

Process returned 0 (0x0)   execution time : 2.660 s
Press any key to continue.



This post has been edited by indyarocks: 26 May 2012 - 11:59 PM


Is This A Good Question/Topic? 0
  • +

Replies To: what's wrong with this alphabetical sorting of string ?

#2 ishkabible  Icon User is offline

  • spelling expret
  • member icon




Reputation: 1622
  • View blog
  • Posts: 5,709
  • Joined: 03-August 09

Re: what's wrong with this alphabetical sorting of string ?

Posted 26 May 2012 - 11:09 PM

what sorting algorithm is this? you're overwriting all the characters in your string in the second loop for 1 thing.

as a side note, there is also std::sort
Was This Post Helpful? 1
  • +
  • -

#3 indyarocks  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 104
  • Joined: 07-March 12

Re: what's wrong with this alphabetical sorting of string ?

Posted 27 May 2012 - 12:02 AM

Thanks Ishka. Yes, I had made a mistake in algorithm. I was trying to use "Insertion sort" algorithm.
Corrected it. Now its working as expected. :)

P.S: I'm learning C++ on my own. And you guys, make me feel that I'm not alone. There is always someone like you people, who are ready to mentor me anytime on any topic. :) MAKING MY LEARNING A JOYFUL EXPERIENCE. THANKS.

This post has been edited by indyarocks: 27 May 2012 - 12:03 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1