selection sort for linked list

I'm trying to sort a linked list by using selection sort algorithm,but it doesn't work.where's the problem?! I test it by myself and it worked.
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<iostream>
using namespace std;
#include<conio.h>

struct node
{
	int value;
	struct node *link;
};

void sort(node**);

int main()
{
	int tmp;
	node *start,*p,*q;
	cin>>tmp;
	p=new node;
	p->value=tmp;
	start=p;
	q=p;
	while(cin>>tmp)
	{
		p=new node;
		p->value=tmp;
		q->link=p;
		q=q->link;
	}
	q->link=NULL;
	sort(&start);
	p=start;
	while(p)
	{
		cout<<
		p->value<<"	";
		p=p->link;
	}
	cout<<endl;

	getch();
	return 0;
}

void sort(node **start)
{
	int tmp,i=0,ind=0;
	node *p,*q;
	p=*start;
	if(p->link)
	{
		tmp=p->value;
		while(p)
		{
			if(p->value<=tmp)
			{
				tmp=p->value;
				ind=i;
			}
			i++;
			p=p->link;
		}
		p=*start;
		for(int j=0;j<--ind;j++)
			p=p->link;
		if(p==*start)
			;
		else
		{
			q=*start;
			*start=p->link;
			p->link=q;
			q=(p->link)->link;
			(p->link)->link=(*start)->link;
			(*start)->link=q;
		}
		sort(&((*start)->link));
	}

}
Last edited on
1
2
        for(int j=0;j<--ind;j++)
            p=p->link;


If ind is the "index" of the node with the smallest value, and you're trying to get to that node, why are you decreasing the value of ind while increasing the value of j?
WOW! thank you so much! I haven't noticed that it happens every time.
Topic archived. No new replies allowed.