sorting linked list

so i have the following code, it inserts a number to a list and then i call my sort function which is below this function, the problem is that my sort function takes forever, is there a way i can implement my insert function so that everytime it inserts a number it inserts it on the correct place

for example

1
2
3
4
5
6
myq.insert(2);
myq.insert(5);
myq.insert(4)
myq.display(); // after this is called it should display 2 4 5



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
void LL::insert(int NewNum)
{

  if(rear == NULL)//CASE:1(if rear is null)                                    
    {
      front = rear = new PCB;
      rear->id = NewNum;
    }
  else//CASE:2(if the list is not empty)                                       
    {
      rear->next = new PCB;
      rear = rear->next;
      rear->id = NewNum;
      rear->next = NULL;
    }
  

  count++;
}

void LL::sort()
{
  int i,j,m,n=0,hold;
  PCB *q, *p, *t;
  for(PCB*q = front ; q ; q=q->next)
    ++n;

  for(i=1 , t = front  ; i<=n-1 ;  t = t->next , ++i)
    for( j=0 , p = front  ; j<n-i ;  p = p->next , ++j)
      if(p->id > (p->next)->id)
        {
          hold = p->id;
          p->id = (p->next)->id;
          (p->next)->id = hold;
        }
}
Topic archived. No new replies allowed.