Skip to main content
gamedev.net
🔒 Locked

alphabetizing elements in a string

Started by DeadFish 3 replies 1.3k views
Original Post
DeadFish
DeadFish
Heres my hack at alphebetizing any old string

#include <cstdio>
#include <string>
#include <iostream>

using namespace std;



void main()
{
	string s1 = "hi there";
	bool changes = true;
	char c;
	int a;

again:
	changes = false;
	a = 0;
	while(a < s1.size() - 1)
	{
		
		if(s1.at(a) > s1.at(a+1))
			{
				changes=true;
				c = s1.at(a+1);
				s1.at(a+1) = s1.at(a);
				s1.at(a) = c;
			}
			a++;
		cout << s1 << "\n";
	}

	if(changes) goto again;

	cout << "s1=" << s1 << "\n";


}

I want to see how else it can be done, preferrably in a more elegant way, as I think the way I did it is probably horrible. -Jason
Fruny
Fruny
Here's mine [smile]

#include <algorithm>#include <string>#include <iostream>using namespace std;int main(){   string s1 = "hi there";   sort(s1.begin(), s1.end());   cout << "s1=" << s1 << "\n";}
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Drew_Benton
Drew_Benton
Quote:
Original post by Fruny
Here's mine [smile]

*** Source Snippet Removed ***


[lol] Fruny, you know you always make me smile.
Fruny
Fruny
Anyway, you could have a look here and there for some pointers. You have implemented bubble sort; std::sort is typically an introsort.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.