Sort name Alphabetically

Nov 18, 2012 at 2:13am
I know there are couple example on the other post. But i haven't studied the most of those kind code.
i only studied #include<cstring> .

There is my idea, I know it's wrong. I don't know how the strcmp defined the letters' value.
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
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

#include <cstring>

class name
{
public:
	char Cname[12];
	name* next;
};

void coutSt(const name*);
int main()
{
	name* head=0;
	char add;
	while(true)
	{
		cout<<"Do you want to add any Name?(Y/N)"<<endl;
		cin>>add;
		name*c = new name;
		if((add=='Y')||(add=='y'))
		{
			
			cout<<"Enter the name."<<endl;
			cin>>c->Cname;
			
		}
		else if((add=='N')||(add=='n'))
			break;

		name * p, *prev; 
		for (p=head, prev=0; p; prev=p, p=p->next) 
			if (strcmp(&p->Cname[1],&c->Cname[1])<0)
				break; 
		c->next = p; 
		if (prev) 
			prev->next = c; 
		else 
			head = c; 
		cout<<endl;
		coutSt(head);
	}
}
void coutSt(const name* c)
{
	cout<<"NAME"<<endl;
	cout<<"------"<<endl;
	const name*p;
	for (p=c;p;p=p->next)
	{
		cout<<p->Cname<<endl;
	}
}



How to improve it to make it work correctly? or any other method to do that?
Last edited on Nov 18, 2012 at 2:14am
Nov 18, 2012 at 2:58am
Can you explain what its supposed to do and how its failing to do that?

All I can tell is you have some kind of linked list.

A word of note:
strcmp(&p->Cname[1],&c->Cname[1])

I haven't got the slightest clue what your trying to do here. Currently it compares the first string to the second string, discounting the first letter. Very odd.

NVM: just read your title. Your trying to sort a linked list. First of all, you need a sorting algorithm. Read this: http://en.wikipedia.org/wiki/Bubble_sort. Second of all, I highly suggest you do not use a linked list to do this. Most easy to read material is written for normal arrays and singly linked lists are hard to use.
Last edited on Nov 18, 2012 at 3:04am
Nov 18, 2012 at 3:04am
name is an array, so what I think is i could only compare the first char of the name. It might be wrong, it's just what I thought.

When I input name, it suppose to insert the name at the right position depending on the alphabetical order.

I said it fails is because according what I put, the order is not right .
Such as: Amy, Bob, Cindy, Dan...
Nov 18, 2012 at 4:00am
closed account (D80DSL3A)
strcmp() function usage:
Arguments are entire strings.
Call like so strcmp( p->Cname, c->Cname );

strcmp compares the entire strings lexicographically (as in dictionary).
strcmp( strA, strB ) returns:
-1 if strA < strB
+1 if strA > strB
0 if strA == strB

@blueberry: He is inserting the elements in order as they are added.
No sorting needed!
Nov 18, 2012 at 8:11am
thanx! I fixed it!
Topic archived. No new replies allowed.