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

New Topic/Question
Reply



MultiQuote







|