How to sort string array alphabetically?

Hi,

I was trying to sort an array of strings alphabetically. Can someone give me an example how to sort an array of strings here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <string>
#include <fstream>

using namespace std;
string stari[1000];
string novi[1000];
int N;

void Citaj()
{
	fstream fajl("spisak.in",ios::in);
	fajl >> N;
	
	for(int i = 1; i <= N; i++)
	{
		getline(fajl,stari[i]);
	}
	
	fajl.close();
}
void Sortiraj()
{
	
	//Selection sort
	string pom;
	for (int i = 1; i <= N-1; i++)
	{
		for(int j=i+1; i <= N; j++)
		{
			
			if(stari[i] > stari[j])
			{
				pom = stari[i];
				novi[i] = stari[j];
				stari[j] = pom;
			}
			
		}
	}

}

void ListajStari()
{
	for(int i=1; i <= N; i++)
		cout << stari[i] << endl;
}
void ListajNovi()
{
	for(int i=1; i <= N; i++)
		cout << novi[i] << endl;
}

int main()
{
	Citaj();
	Sortiraj();
	ListajStari();
	cout << "----------------" << endl;
	ListajNovi();
	system("pause");
	return 0;
}


Function Sortiraj() should sort the array of Strings using the selection sort technique but It does not work because program just crashes when it tries to compare two strings with > .
So does anybody have already written function for sorting array of strings.

I would really appreciate if someone would give me an example for sorting array of strings.
(Note: I don't want char * sorting I want string sorting)

Also are there already made sorting functions in C++ (I've hear of qsort but I don't know how to use it also show me some examples of array sorting methods)

Thanks in advance!
A couple of things I noticed...

1
2
3
4
5
6
7
8
9
void Citaj()
{
    fstream fajl("in.txt",ios::in);
    fajl >> N; fajl.get(); // <- add this here...
    //...to get rid of the newline character,
    //or the first getline will read an empty string

    //...
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void Sortiraj()
{
    //Selection sort
    string pom;
    for (int i = 1; i <= N-1; i++)
    {
        //careful here, you need j, not i
        for(int j=i+1; i <= N; j++)
        {
            //don't do it like this.
            //copy stari to novi first
            //in a separate function
            //and then sort novi
            if(stari[i] > stari[j])
            {
                pom = stari[i];
                novi[i] = stari[j];
                stari[j] = pom;
            }
        }
    }
}

Last edited on
Topic archived. No new replies allowed.