Sorting a linked list alphabetical.

Nov 26, 2012 at 9:04pm
Hi. Te problem asks for me to read 10 names from a file, put them in a single linked list and sort them. This is what I've done so far.......is it ok?
Cheers!

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

struct list1
{ string s;
list1 *next;
}
typedef list1 *list;

int main()
{
string file;
list *first, *last, *p;
first = last = new list;
list *prev = new list;


cout<<"Input the file name from where you want to read:";
cin>>file;


ifstream fin;
fin.open(file.c_str());
getline(fin,s);
fin>>first->s;
first->next=NULL;

while(!fin.eof())
{ last->next=new list;
last=last->next;
getline(fin,s);
fin>>last->s;
last->next=NULL;
}

for (list *i = first; i != NULL; i = i->next) {
cout << i->s << " ";
}

cout << endl;

bool ok = false;

while (!ok) {
ok = true;
prev->next = first;

for (list *i = first; i != last; i = i->next) {
if (i->s.compare(i->next->s) > 0) {
prev->next = i->next;
i->next = i->next->next;
prev->next->next = i;

ok = false;
}

prev = prev->next;
}

}

cout << "Sorted List: \n";

for (list *i = first; i != NULL; i = i->next) {
cout << i->s << " ";
}

cout << endl;

return 0;
}
Nov 27, 2012 at 1:26am
So let me get this straight, you want to print a list of names in alphabetical order?
Nov 27, 2012 at 3:40pm
Yes.
I read some name from a file. Put them in a list and then want to sort them. I think the sorting alg is wrong.
Nov 27, 2012 at 6:32pm
Yes I do have a sorting program that sorts integers from least to greatest, and you can just change all the ints to strings in order to make it into alphabetical order for words. I will send you this program when I get home and you could take a look at the algorithm I used.
Nov 27, 2012 at 8:43pm
Cheers!
Nov 28, 2012 at 5:18pm
#include <iostream>

using namespace std;

void spot(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}

int main(int argc, const char * argv[])
{

int a[5];
for(int i=0; i<5; i++)
{
cin>>a[i];

}


int s = 0;

do {
s=0;
for(int x=0; x<4; x++)
{
if(a[x]>a[x+1])
{
spot(a[x], a[x+1]);
s++;
}
}

}while(s!=0);

cout<<"\n";

for(int b=0; b<5; b++)
{
cout<<a[b]<<"\n";
}

return 0;
}
Nov 28, 2012 at 5:20pm
This program sorts numbers in an array from least to greatest. If you want to read the names from a file and put them into a dynamic array, you have to use the fstream library, and for the dynamic array you need to use pointer references which you can look up.
Nov 28, 2012 at 5:20pm
You actually might not need to use dynamic arrays.
Nov 28, 2012 at 5:21pm
To change the program from sorting numbers from least to greatest to strings from least to greatest, you have to change the ints to strings.
Topic archived. No new replies allowed.